需要返回两组具有两个不同where子句的数据

时间:2014-08-11 23:40:30

标签: mysql sql

我有一张跟踪交易的表。

该表设置为:

transactions:

id, account_id, budget_id, points, type

我需要返回每个budget_id的点数之和,其中type ='allocation'和type ='issue'的点数之和

我知道如何在一个查询中执行每个操作,但不能同时执行。

预期结果集:

budget_id   allocated   issued
   434       200000      100
   242       100000      5020
   621       45000       3940

2 个答案:

答案 0 :(得分:6)

SELECT budget_id, 
       SUM(IF(type = 'allocation', points, 0)) AS allocated,
       SUM(IF(type = 'issue', points, 0)) AS issued
FROM transactions
GROUP BY budget_id

答案 1 :(得分:2)

    select budget_ID, 
     sum(case when type = 'allocated' then points else 0 end) as allocated,
     sum(case when type = 'issued' then points else 0 end) as issued
     ..rest of your query...
    group by budget_ID

只有在满足某个标准时,才能使用案例进行求和。