提问人:Brad 提问时间:8/12/2014 最后编辑:LeoBrad 更新时间:2/20/2015 访问量:489
需要返回两组带有两个不同 where 子句的数据
need to return two sets of data with two different where clauses
问:
我有一个跟踪交易的表。
该表的设置如下:
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
答:
7赞
Barmar
8/12/2014
#1
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
3赞
Twelfth
8/12/2014
#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
仅当满足特定条件时,才能使用案例求和。
评论
SELECT budget_id, A.all_sum AS allocated, I.iss_sum AS issued FROM transactions INNER JOIN (SELECT SUM(points) AS all_sum FROM transactions WHERE type='Allocation') AS A INNER JOIN (SELECT SUM(points) FROM transactions WHERE type='Issue') AS I