SELECT * FROM
(
SELECT ID,
CODE,
CAST(SUM(QTY) AS INT) AS G_QTY,
CAST(SUM(Amount) AS INT) AS AmountUsed
FROM Tbl_Used
WHERE CODE IN ('ABC','DEF','GHI')
GROUP BY ID,CODE
) AS S
PIVOT
(
SUM(AmountUsed)
FOR CODE IN(ABC,DEF)
) AS Pivot1
我也希望将G_QTY用于CODE IN('GHI')
结果应该是:
ID ABC DEF GHI
1 10 20 30
表数据
ID CODE QTY AMOUNT
1122 ABC 546 789653
456 GHI 5644 65433213
1455 DEF 99978 464646
1122 ABC 6565 98464
1455 DEF 88933 7933
2454 GHI 88989 5522
456 ABC 108309 789653
2454 DEF 125414 65433213
4452 GHI 142519 464646
3120 GHI 159624 98464
456 GHI 176729 7933
3120 ABC 193834 5522
456 GHI 210938 125414
4452 DEF 228043 142519
1455 ABC 245148 159624
3120 DEF 262253 176729
数据不实,但与生产环境相似
答案 0 :(得分:2)
可能是这样的:
SELECT ID,Max(ABC) AS ABC,Max(DEF) As DEF,Max(GHI) AS GHI
FROM
(
SELECT ID,
CODE,
CODE As CODE1,
CAST(SUM(QTY) AS INT) AS G_QTY,
CAST(SUM(Amount) AS INT) AS AmountUsed
FROM Tbl_Used
WHERE CODE IN ('ABC','DEF','GHI')
GROUP BY ID,CODE
) AS S
PIVOT
(
SUM(AmountUsed)
FOR CODE IN([ABC],[DEF])
) AS Pivot1
PIVOT
(
SUM(G_QTY)
FOR CODE1 IN([GHI])
) AS Pivot2
Group By ID
<强> FIDDLE DEMO 强>
输出:
ID ABC DEF GHI
456 789653 (null) 393311
1122 888117 (null) (null)
1455 159624 472579 (null)
2454 (null) 65433213 88989
3120 5522 176729 159624
4452 (null) 142519 142519
答案 1 :(得分:2)
我重写了查询。这样就不需要两个数据透视,也因为枢轴已经聚合并且不需要内部查询分组。
所以我的建议如下:
测试数据
DECLARE @tbl TABLE(ID INT,CODE VARCHAR(5),QTY INT, AMOUNT INT)
INSERT INTO @tbl
VALUES
(1122,'ABC',546,789653),
(456,'GHI',5644,65433213),
(1455,'DEF',99978,464646),
(1122,'ABC',6565,98464),
(1455,'DEF',88933,7933),
(2454,'GHI',88989,5522),
(456,'ABC',108309,789653),
(2454,'DEF',125414,65433213),
(4452,'GHI',142519,464646),
(3120,'GHI',159624,98464),
(456,'GHI',176729,7933),
(3120,'ABC',193834,5522),
(456,'GHI',210938,125414),
(4452,'DEF',228043,142519),
(1455,'ABC',245148,159624),
(3120,'DEF',262253,176729)
<强>查询强>
SELECT
*
FROM
(
SELECT
tbl.ID,
tbl.CODE,
(
CASE
WHEN tbl.CODE='GHI'
THEN QTY
ELSE Amount
END
) AS ValueToPivot
FROM
@tbl AS tbl
WHERE tbl.CODE IN ('ABC','DEF','GHI')
) AS SourceTable
PIVOT
(
SUM(ValueToPivot)
FOR CODE IN ([ABC],[DEF],[GHI])
) AS pvt
这会得到结果:
ID ABC DEF CHI
------------------------------------
456 789653 NULL 393311
1122 888117 NULL NULL
1455 159624 472579 NULL
2454 NULL 65433213 88989
3120 5522 176729 159624
4452 NULL 142519 142519