【发布时间】:2011-06-07 16:17:38
【问题描述】:
我想对一列求和,但基于不同的交易类型,并且这些总和只显示在一行中。
My 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”列的所有总数?
【问题讨论】:
标签: sql tsql sql-server-2000