3

我有下表

 #   amount   type
 1     10      0
 1     10      0
 1     5       1
 1     5       1
 2     10      0
 2     10      0
 2     5       1
 2     5       1

其中 0 表示现金,1 表示类型列中的信用

问题是找到每个 ID 的现金使用和信用使用的总和以及总金额。

我正在寻找获得以下结果的查询

 #   cash credit total
 1    20    10    30 
 2    20    10    30

如果可能,我想使用一个查询

谢谢

4

3 回答 3

4
SELECT id, 
SUM(CASE WHEN type = 0 THEN amount ELSE 0 END) as "cash",
SUM(CASE WHEN type = 1 THEN amount ELSE 0 END) as "credit", 
SUM(amount) as "total"
FROM your_table
GROUP BY id
于 2013-06-23T12:04:44.197 回答
2
SELECT
  num,
  SUM(CASE WHEN type=0 THEN amount END) cash,
  SUM(CASE WHEN type=1 THEN amount END) credit,
  SUM(amount) total
FROM
  yourtable
GROUP BY num
于 2013-06-23T12:05:00.170 回答
0
select id,
       sum(amount) as "total",
       CASE WHEN type = 0 THEN amount ELSE 0 END as "cash",
       CASE WHEN type = 1 THEN amount ELSE 0 END as "credit",
  from table
 group by id
于 2013-06-23T12:07:43.580 回答