读书人

请问重复数据行列互换有关问题

发布时间: 2012-08-16 12:02:15 作者: rapoo

请教重复数据行列互换问题
RT

-------------
TABLE

IDDATETIMECODE
12012-7-7A
12012-7-7B
12012-7-17C
12012-7-24D
22012-7-11A
22012-7-11B
32012-7-16A
32012-7-16B
32012-7-17C
32012-7-23D
----------------------
如何实现如下查询结果?3Q
IDA B C D
12012-7-72012-7-72012-7-172012-7-24
22012-7-112012-7-11NULL NULL
32012-7-162012-7-162012-7-172012-7-23


[解决办法]

SQL code
create table tb(ID int, DATETIME datetime ,code varchar(2))  insert into tb values('1','2012-7-7','A')  insert into tb values('1','2012-7-7','B')  insert into tb values('1','2012-7-17','C')  insert into tb values('1','2012-7-24','D' )  go    select ID, CODE,[DATETIME]=stuff((select ','+[DATETIME] from tb  where ID=tb.ID for xml path('')), 1, 1, '')  from tb  group by ID   /*  ID    A     B       C          D  ----------- --------------------  1  2012-7-7 2012-7-7 2012-7-17 2012-7-24
[解决办法]
http://topic.csdn.net/u/20080612/22/c850499f-bce3-4877-82d5-af2357857872.html
[解决办法]
SQL code
if object_id('[tb]') is not null drop table [tb]gocreate table [tb]([ID] int,[DATETIME] datetime,[CODE] varchar(1))insert [tb]select 1,'2012-7-7','A' union allselect 1,'2012-7-7','B' union allselect 1,'2012-7-17','C' union allselect 1,'2012-7-24','D' union allselect 2,'2012-7-11','A' union allselect 2,'2012-7-11','B' union allselect 3,'2012-7-16','A' union allselect 3,'2012-7-16','B' union allselect 3,'2012-7-17','C' union allselect 3,'2012-7-23','D'godeclare @sql varchar(8000)select @sql=isnull(@sql+',','')  +'max(case when code='''+code+''' then convert(varchar(10),datetime,120) end) as ['+code+']'from(select distinct code from tb) texec('select id,'+@sql+' from tb group by id')/**id          A          B          C          D----------- ---------- ---------- ---------- ----------1           2012-07-07 2012-07-07 2012-07-17 2012-07-242           2012-07-11 2012-07-11 NULL       NULL3           2012-07-16 2012-07-16 2012-07-17 2012-07-23(3 行受影响)**/ 

读书人网 >SQL Server

热点推荐