日期:2014-05-17 浏览次数:20938 次
id codeid listdate quantity 1 123 2012-05-01 10 2 123 2012-02-02 20 3 456 2012-09-01 30 3 123 2012-01-03 40 4 456 2012-10-03 50 5 789 2012-10-08 60
id codeid listdate 1 123 2012-05-05 2 456 2012-09-04 3 789 2012-09-08 4 098 2012-09-23
id codeid litdate f1 f3 1 123 2012-05-05 2012-05-01,2012-02-02 10,20 2 456 2012-09-04 2012-09-01 30 3 789 2012-09-08 4 098 2012-09-23
if OBJECT_ID('A1') is not null drop table A1 create table A1(codeid nvarchar(10),listdate datetime,quantity int) insert into A1 select '123','2012-05-01',10 union all select '123','2012-02-02',20 union all select '456','2012-09-01',30 union all select '123','2012-01-03',40 union all select '456','2012-10-03',50 union all select '789','2012-10-08',60 if OBJECT_ID('A2') is not null drop table A2 create table A2(codeid nvarchar(10),listdate datetime) insert into A2 select '123','2012-05-05' union all select '456','2012-09-04' union all select '789','2012-09-08' union all select '098','2012-09-23' select distinct A2.codeid,convert(nvarchar(10),A2.listdate,120) as listdate, Stuff((select top 2 ','+convert(nvarchar(10),listdate,120) from A1 where codeid=A2.codeid and listdate<A2.listdate order by listdate desc for XML path('')),1,1,'') as f1, Stuff((select top 2 ','+convert(nvarchar(10),quantity) from A1 where codeid=A2.codeid and listdate<A2.listdate order by listdate desc for XML path('')),1,1,'') as f3 from A2 left join A1 on A1.codeid=A2.codeid /* codeid listdate f1 f3 098 2012-09-23 NULL NULL 123 2012-05-05 2012-05-01,2012-02-02 10,20 456 2012-09-04 2012-09-01 30 789 2012-09-08 NULL NULL */