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

need to return two sets of data with two different where clauses

提问人:Brad 提问时间:8/12/2014 最后编辑:LeoBrad 更新时间:2/20/2015 访问量:489

问:

我有一个跟踪交易的表。

该表的设置如下:

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
MySQL 数据库

评论

0赞 scrowler 8/12/2014
字段列表中的子查询或子查询的联接
0赞 scrowler 8/12/2014
例如,帮助您入门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
0赞 Twelfth 8/12/2014
@scrowler - 将起作用,但如果分组相同,则可以使用大小写到条件总和。
0赞 halfer 2/20/2015
嗨,布拉德。以下任何一个答案对您有帮助吗?如果是这样,请考虑将其中一个标记为已接受。

答:

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

仅当满足特定条件时,才能使用案例求和。