你必须UNPIVOT
先到你的桌子然后PIVOT
再
WITH unpivot_details AS
(
SELECT WorkWeek, Type, Value
FROM
(
SELECT WorkWeek, CometsFT, CometsTR, CSP, MaxCIMFT, MaxCIMTR, MaxCIMWS, STD
FROM tblLotTrackingDetails
) s
UNPIVOT
(
Value FOR Type IN (CometsFT, CometsTR, CSP, MaxCIMFT, MaxCIMTR, MaxCIMWS, STD)
) s
)
SELECT Type RowLabels,
WW1, WW2, WW3, WW4, WW5, WW6, WW7, WW8, WW9, WW10
FROM
(
SELECT WorkWeek, Type, Value
FROM unpivot_details
UNION ALL
SELECT WorkWeek, 'Total', SUM(Value) Value
FROM unpivot_details
GROUP BY WorkWeek
) s
PIVOT
(
SUM(Value) FOR WorkWeek IN(WW1, WW2, WW3, WW4, WW5, WW6, WW7, WW8, WW9, WW10)
) p
ORDER BY CASE WHEN Type = 'Total' THEN 1 ELSE 0 END,
Type
样本输出:
| 行标签 | 第一次世界大战 | 二战 | 二战 | 二战 | 二战 | 二战 | 二战 | 二战 | 二战 | WW10 |
|-----------|-----|-----|-----|-----|-----|-----|- ----|-----|-----|------|
| 彗星FT | 42 | 50 | 30 | 45 | 25 | 36 | 26 | 33 | 35 | 35 |
| 彗星TR | 20 | 14 | 30 | 28 | 24 | 14 | 21 | 18 | 21 | 9 |
| 太阳能电池板 | 6 | 4 | 1 | 7 | 9 | 8 | 8 | 2 | 4 | 3 |
| 最大CIMFT | 52 | 58 | 105 | 77 | 42 | 39 | 34 | 23 | 34 | 19 |
| 最大CIMTR | 21 | 2 | 7 | 9 | 34 | 4 | 5 | 7 | 7 | 9 |
| 最大CIMWS | 28 | 29 | 59 | 82 | 24 | 26 | 19 | 20 | 40 | 21 |
| 性病 | 3 | 40 | 2 | 8 | 2 | 5 | 5 | 2 | 9 | 2 |
| 总计 | 172 | 197 | 234 | 256 | 160 | 132 | 118 | 105 | 150 | 98 |
这是SQLFiddle演示
根据您的评论进行更新。此查询将提取第 11 周到第 15 周的数据。
WITH unpivot_details AS
(
SELECT WorkWeek, Type, Value
FROM
(
SELECT WorkWeek, CometsFT, CometsTR, CSP, MaxCIMFT, MaxCIMTR, MaxCIMWS, STD
FROM tblLotTrackingDetails
WHERE WorkWeek IN ('WW11', 'WW12', 'WW13', 'WW14', 'WW15')
) s
UNPIVOT
(
Value FOR Type IN (CometsFT, CometsTR, CSP, MaxCIMFT, MaxCIMTR, MaxCIMWS, STD)
) s
)
SELECT Type RowLabels,
WW11, WW12, WW13, WW14, WW15
FROM
(
SELECT WorkWeek, Type, Value
FROM unpivot_details
UNION ALL
SELECT WorkWeek, 'Total', SUM(Value) Value
FROM unpivot_details
GROUP BY WorkWeek
) s
PIVOT
(
SUM(Value) FOR WorkWeek IN(WW11, WW12, WW13, WW14, WW15)
) p
ORDER BY CASE WHEN Type = 'Total' THEN 1 ELSE 0 END,
Type
这是SQLFiddle演示