如果您使用的是SQL Server 2005(或更高版本),則下面是查詢,並附有概念驗證。享受:
--Proof of concept structure and data creation
create table #t (ID int, TestID int, Elapsed int, ActionID varchar(10))
insert into #t (ID, TestID, Elapsed, ActionID) values
(1, 1, 16, 'a1'),
(2, 1, 17, 'a2'),
(3, 1, 13, 'a3'),
(4, 1, 14, 'a4'),
(5, 2, 19, 'a1'),
(6, 2, 21, 'a2'),
(7, 2, 11, 'a3'),
(8, 2, 22, 'a4');
--end of structure and data creating
--actual query starts here
DECLARE @cols VARCHAR(1000)
DECLARE @sqlquery VARCHAR(2000)
SELECT @cols = STUFF((SELECT distinct ',' + QuoteName([ActionID])
FROM #t FOR XML PATH('')), 1, 1, '')
SET @sqlquery = 'SELECT * FROM
(SELECT TestID, Elapsed, ActionID
FROM #t ) base
PIVOT (SUM(Elapsed) FOR [ActionID]
IN (' + @cols + ')) AS finalpivot'
--Depending on your approach, you might want to use MAX instead of SUM.
--That will depend on your business rules
EXECUTE (@sqlquery)
--query ends here
--proof of concept cleanup
drop table #t;
無論你在ActionID
有多少不同的值,這將工作。它用PIVOT
動態地組裝一個查詢。您可以通過動態列來執行PIVOT的唯一方法是動態組裝查詢,這可以在SQL Server中完成。
其他例子: