我想弄清楚哪種方式更有效率。我試圖使用Sql小提琴,但它似乎沒有識別PIVOT或UNION 我可以查看哪些工具或統計數據來確定哪些更有效。樞軸VS案例T-sql效率
CREATE TABLE T
(
PersonNum INT
,WeekOf DATETIME
,ActivityType1 INT
,ActivityType2 INT
,Hours INT
)
INSERT INTO T VALUES(1,'11/2/2014',5,0,40)
INSERT INTO T VALUES(1,'11/2/2014',1,0,5)
INSERT INTO T VALUES(1,'11/2/2014',1,0,8)
INSERT INTO T VALUES(1,'11/2/2014',2,1,6)
INSERT INTO T VALUES(1,'11/2/2014',2,2,2)
INSERT INTO T VALUES(1,'11/2/2014',2,3,9)
INSERT INTO T VALUES(1,'11/2/2014',2,4,7)
INSERT INTO T VALUES(1,'11/9/2014',5,0,40)
INSERT INTO T VALUES(1,'11/9/2014',1,0,2)
INSERT INTO T VALUES(1,'11/9/2014',1,0,6)
INSERT INTO T VALUES(1,'11/9/2014',2,1,7)
INSERT INTO T VALUES(1,'11/9/2014',2,2,2)
INSERT INTO T VALUES(1,'11/9/2014',2,3,3)
INSERT INTO T VALUES(1,'11/9/2014',2,4,5)
方法1
SELECT
PersonNum
, WeekOf
, SUM(CASE WHEN ActivityType1 = 5 THEN Hours ELSE 0 END) AS Beginning
, SUM(CASE WHEN ActivityType1 = 1 THEN Hours ELSE 0 END) AS Plus
, SUM(CASE WHEN ActivityType1 = 2 AND ActivityType2 <> 3 THEN Hours ELSE 0 END) AS Minus
, SUM(CASE WHEN ActivityType1 = 2 AND ActivityType2 = 3 THEN Hours ELSE 0 END) AS MinusSpecial
FROM T
GROUP BY
PersonNum
, WeekOf
方法2
SELECT
PersonNum
, WeekOf
, [Beginning]
, [Plus]
, [Minus]
, [Minus Special]
FROM
(
SELECT
PersonNum
, WeekOf
, 'Beginning' AS ColumnType
, Hours
FROM T
WHERE
ActivityType1 = 5
UNION
SELECT
PersonNum
, WeekOf
, 'Plus' AS ColumnType
, Hours
FROM T
WHERE
ActivityType1 = 1
UNION
SELECT
PersonNum
, WeekOf
, 'Minus' AS ColumnType
, Hours
FROM T
WHERE
ActivityType1 = 2
AND ActivityType2 <> 3
UNION
SELECT
PersonNum
, WeekOf
, 'Minus Special' AS ColumnType
, Hours
FROM T
WHERE
ActivityType1 = 2
AND ActivityType2 = 3
) Data
PIVOT
(SUM(Hours)
FOR ColumnType IN ([Beginning]
,[Plus]
,[Minus]
,[Minus Special])
) pvt
看看這篇文章。它涵蓋了執行此類查詢的不同方式並探討了性能。 http://www.sqlservercentral.com/articles/T-SQL/63681/ – 2014-11-14 19:29:17