我的表格如下:
DeviceNumber PayWay Money
000001 A 1
000002 B 2
000001 A 1
000001 B 1.2
000002 A 2.6
我想得到结果:
DeviceNumber Total A B
000001 3.2 2 1.2
000002 4.6 2.6 2
有没有sql实现这个?非常感谢你!
答案 0 :(得分:1)
SELECT DeviceNumber, SUM(CASE WHEN PayWay='A' THEN Money END) A,
SUM(CASE WHEN PayWay='B' THEN Money END) B,SUM(Money) TOTAL FROM TABLE
GROUP BY DeviceNumber
您可以尝试以上查询。
答案 1 :(得分:1)
是的,您可以像这样使用SUM和CASE
SELECT DeviceNumber,sum(money) as Total,
SUM(
CASE
WHEN PayWay='A' THEN Money ELSE 0
END) as A,
SUM(
CASE
WHEN PayWay='B' THEN Money ELSE 0
END) as B
FROM MyTable
GROUP BY DeviceNumber
ORDER BY DeviceNumber