我正在使用 SQL 2005。我试图转置(因为没有更好的词),用户列值以使其值作为实际列名,然后用阈值填充它。用户数量是动态的。它可以是 3 个或更多,但不超过 35 个。如您所见,每个操作的用户数将始终相同。谢谢您的帮助。
-- tbl_actions
Title GrpName Action User Threshold
Title1 Group1 Action1 A 180:10:Green
Title1 Group1 Action1 B 180:30:Yellow
Title1 Group1 Action1 C 180:45:Yellow
Title1 Group1 Action2 A 360:10:Green
Title1 Group1 Action2 B 360:23:Yellow
Title1 Group1 Action2 C 360:50:Red
Title1 Group1 Action4 A 180:10:Green
Title1 Group1 Action4 B 180:35:Yellow
Title1 Group1 Action4 C 180:25:Yellow
-- Result sought
Title GrpName Action A B C
Title1 Group1 Action1 180:10:Green 180:30:Yellow 180:45:Yellow
Title1 Group1 Action2 360:10:Green 360:23:Yellow 360:50:Red
Title1 Group1 Action4 180:10:Green 180:35:Yellow 180:25:Yellow
--For table data
Select 'Title1' as Title, 'Group1' as GroupName, 'Action1' as Action, 'A' as UserName, '180:10:Green:2/20/2013' as Threshold
UNION
Select 'Title1' as Title, 'Group1' as GroupName, 'Action1' as Action, 'B' as UserName, '180:30:Yellow:2/22/2013' as Threshold
UNION
Select 'Title1' as Title, 'Group1' as GroupName, 'Action1' as Action, 'C' as UserName, '180:45:Yellow:2/21/2013' as Threshold
UNION
Select 'Title1' as Title, 'Group1' as GroupName, 'Action2' as Action, 'A' as UserName, '360:10:Green:2/18/2013' as Threshold
UNION
Select 'Title1' as Title, 'Group1' as GroupName, 'Action2' as Action, 'B' as UserName, '360:23:Yellow:2/1/2013' as Threshold
UNION
Select 'Title1' as Title, 'Group1' as GroupName, 'Action2' as Action, 'C' as UserName, '360:50:Red:2/3/2013' as Threshold
UNION
Select 'Title1' as Title, 'Group1' as GroupName, 'Action4' as Action, 'A' as UserName, '180:10:Green:2/5/2013' as Threshold
UNION
Select 'Title1' as Title, 'Group1' as GroupName, 'Action4' as Action, 'B' as UserName, '180:35:Yellow:2/22/2013' as Threshold
UNION
Select 'Title1' as Title, 'Group1' as GroupName, 'Action4' as Action, 'C' as UserName, '180:25:Yellow:2/11/2013' as Threshold
--Result
Select 'Title1' as Title, 'Group1' as GroupName, 'Action1' as Action, '180:10:Green:2/20/2013' as 'A', '180:30:Yellow:2/22/2013' as 'B','180:45:Yellow:2/21/2013' as 'C'
UNION
Select 'Title1' as Title, 'Group1' as GroupName, 'Action2' as Action, '360:10:Green:2/18/2013' as 'A', '360:23:Yellow:2/1/2013' as 'B','360:50:Red:2/3/2013' as 'C'
UNION
Select 'Title1' as Title, 'Group1' as GroupName, 'Action3' as Action, '180:10:Green:2/5/2013' as 'A', '180:35:Yellow:2/22/2013' as 'B','180:25:Yellow:2/11/2013' as 'C'