我想整理一列,但是基于不同的交易类型,并且这些总和只出现在一行中。
我的SQL(SQL Server 2000)如下所示:
SELECT c.customername,
CASE WHEN t.transactiontypekey IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19) THEN SUM(t.tranamount) ELSE 0 END as 'Tot-Exp',
CASE WHEN t.transactiontypekey IN (20,21,22,23,30,32,34,36) THEN SUM(t.tranamount) ELSE 0 END as 'Tot-Rev',
CASE WHEN t.transactiontypekey IN (31,33,35,37) THEN SUM(t.tranamount) ELSE 0 END as 'Tot-Fee'
FROM customers c, transactions t
WHERE c.customerkey = t.customerkey
GROUP BY c.customername, t.transactiontypekey
ORDER BY c.customername
在上面的SQL中,交易类型分为费用,收入和费用,上面的输出显示为:
customernameTot-Exp Tot-Rev Tot-Fee
CUSTOMER1 13.3900 .0000 .0000
CUSTOMER1 .0000 549.0000 .0000
CUSTOMER1 .0000 .0000 60.0000
CUSTOMER1 .0000 .0000 .0000
如何让我的输出看起来像:
customername Tot-Exp Tot-Rev Tot-Fee
CUSTOMER1 13.390 549.00 60.000
每个客户只有一行,只有那一行中't.tranamount'列的所有总数?
答案 0 :(得分:4)
总结CASE
表达式本身;
SUM(CASE WHEN t.transactiontypekey IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19) THEN t.tranamount ELSE 0 END) as 'Tot-Exp',
从t.transactiontypekey
删除GROUP BY
。