关于写sql语句的写法
表#a1如下:
id codeid listdate quantity1 123 2012-05-01 102 123 2012-02-02 20 3 456 2012-09-01 303 123 2012-01-03 404 456 2012-10-03 505 789 2012-10-08 60
id codeid listdate1 123 2012-05-052 456 2012-09-043 789 2012-09-08 4 098 2012-09-23
id codeid litdate f1 f31 123 2012-05-05 2012-05-01,2012-02-02 10,202 456 2012-09-04 2012-09-01 303 789 2012-09-08 4 098 2012-09-23
if OBJECT_ID('A1') is not null drop table A1create table A1(codeid nvarchar(10),listdate datetime,quantity int)insert into A1select '123','2012-05-01',10 union allselect '123','2012-02-02',20 union allselect '456','2012-09-01',30 union allselect '123','2012-01-03',40 union allselect '456','2012-10-03',50 union allselect '789','2012-10-08',60if OBJECT_ID('A2') is not null drop table A2create table A2(codeid nvarchar(10),listdate datetime)insert into A2select '123','2012-05-05' union allselect '456','2012-09-04' union allselect '789','2012-09-08' union allselect '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 f3098 2012-09-23 NULL NULL123 2012-05-05 2012-05-01,2012-02-02 10,20456 2012-09-04 2012-09-01 30789 2012-09-08 NULL NULL*/