日期:2014-05-18 浏览次数:20598 次
declare @T table (ID varchar(3),[User] varchar(2),Date varchar(2),Flow varchar(2)) insert into @T select 'id1','u1','d1','f1' union all select 'id1','u2','d2','f2' union all select 'id1','u3','d3','f3' union all select 'id2','u4','d4','f2' union all select 'id2','u5','d5','f3' select id, f1_user=max(case when flow='f1' then [user] else '' end), f1_date=max(case when flow='f1' then date else '' end), f2_user=max(case when flow='f2' then [user] else '' end), f2_date=max(case when flow='f2' then date else '' end), f3_user=max(case when flow='f3' then [user] else '' end), f3_date=max(case when flow='f3' then date else '' end) from @t group by id /* id f1_user f1_date f2_user f2_date f3_user f3_date ---- ------- ------- ------- ------- ------- ------- id1 u1 d1 u2 d2 u3 d3 id2 u4 d4 u5 d5 */
------解决方案--------------------
create table tb(ID varchar(10),[User] varchar(10),Date varchar(10),Flow varchar(10)) insert into tb select 'id1' ,'u1' ,'d1' ,'f1' union all select 'id1' ,'u2' ,'d2' ,'f2' union all select 'id1' ,'u3' ,'d3' ,'f3' union all select 'id2' ,'u4' ,'d4' ,'f2' union all select 'id2' ,'u5' ,'d5' ,'f3' go declare @sql varchar(8000) set @sql = 'select ID' select @sql = @sql + ',max(case Flow when '''+Flow+''' then [User] else '''' end) as ['+Flow+'_User]' + ',max(case Flow when '''+Flow+''' then Date else '''' end) as ['+Flow+'_Date]' from (select distinct Flow from tb)t select @sql = @sql + ' from tb group by ID' exec(@sql) drop table tb /********** ID f1_User f1_Date f2_User f2_Date f3_User f3_Date ---------- ---------- ---------- ---------- ---------- ---------- ---------- id1 u1 d1 u2 d2 u3 d3 id2 u4 d4 u5 d5 (2 行受影响)