我有一个查询已经转动与交易数据相关的数据。我有一个包含客户编号,交易类型和交易金额的表。
我的原始查询返回了每个客户按交易类型细分的交易总数。它在下面:
;WITH query AS
(
SELECT customernum,[Cash],[Card]
FROM (
transactions
)
AS source
PIVOT
(
COUNT(TransType) FOR TransType IN ([Cash],[Card])
)
AS pvt
) SELECT customernum AS 'Customer Number', SUM([Cash]) AS 'Cash Transactions',
SUM([Card]) AS 'Card Transactions' FROM query
GROUP BY customernum
ORDER BY customernum
我现在需要将总值添加到查询中,但仍按事务类型细分。
例如,来自表格'交易的样本数据'是:
╔═════════════╦═══════════╦════════╗ ║ CustomerNum ║ TransType ║ Amount ║ ╠═════════════╬═══════════╬════════╣ ║ 111 ║ Cash ║ 5 ║ ║ 111 ║ Card ║ 5 ║ ║ 111 ║ Cash ║ 5 ║ ║ 111 ║ Cash ║ 5 ║ ║ 111 ║ Card ║ 5 ║ ║ 222 ║ Card ║ 5 ║ ║ 222 ║ Cash ║ 5 ║ ║ 222 ║ Card ║ 5 ║ ║ 333 ║ Cash ║ 5 ║ ║ 333 ║ Cash ║ 5 ║ ║ 333 ║ Cash ║ 5 ║ ╚═════════════╩═══════════╩════════╝
我的原始查询产生了这个结果:
╔═════════════╦══════╦══════╗ ║ CustomerNum ║ Cash ║ Card ║ ╠═════════════╬══════╬══════╣ ║ 111 ║ 3 ║ 2 ║ ║ 222 ║ 1 ║ 2 ║ ║ 333 ║ 3 ║ 0 ║ ╚═════════════╩══════╩══════╝
我现在需要它来回复:
╔═════════════╦══════╦═════════════╦══════╦═════════════╗ ║ CustomerNum ║ Cash ║ Cash Amount ║ Card ║ Card Amount ║ ╠═════════════╬══════╬═════════════╬══════╬═════════════╣ ║ 111 ║ 3 ║ 15 ║ 2 ║ 10 ║ ║ 222 ║ 1 ║ 5 ║ 2 ║ 10 ║ ║ 333 ║ 3 ║ 15 ║ 0 ║ 0 ║ ╚═════════════╩══════╩═════════════╩══════╩═════════════╝
答案 0 :(得分:2)
只需使用条件聚合:
SELECT CustomerNum,
SUM(CASE WHEN TransType = 'Cash' THEN 1 ELSE 0 END) AS cash,
SUM(CASE WHEN TransType = 'Cash' THEN amount ELSE 0 END) AS cash_amount,
SUM(CASE WHEN TransType = 'Card' THEN 1 ELSE 0 END) AS card,
SUM(CASE WHEN TransType = 'Card' THEN amount ELSE 0 END) AS card_amount
FROM transactions
GROUP BY CustomerNum;
答案 1 :(得分:0)
考虑将两个透视查询用作派生表:
SELECT t1.customernum, t1.Cash, t2.Cash As [Cash Amount],
t1.Card, t2.Card As [Card Amount]
FROM
(SELECT * FROM
(SELECT customernum, TransType
FROM transactions) AS src1
PIVOT
(
COUNT(TransType) FOR TransType IN ([Cash],[Card])
)
AS pvt1) As t1
INNER JOIN
(SELECT * FROM
(SELECT customernum, TransType, Amount
FROM transactions) AS src2
PIVOT
(
SUM(Amount) FOR TransType IN ([Cash],[Card])
)
AS pvt2) As t2
ON t1.customernum = t2.customernum