【问题标题】:need to return two sets of data with two different where clauses需要用两个不同的where子句返回两组数据
【发布时间】:2014-10-04 22:04:32
【问题描述】:

我有一张记录交易的表格。

表格设置为:

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

【问题讨论】:

  • 字段列表中的子查询或子查询的连接
  • 例如让你开始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
  • @scrowler - 会起作用,但如果分组相同,您可以使用大小写条件求和。
  • 嗨布拉德。以下任何一个答案对您有帮助吗?如果是这样,请考虑将其中一项标记为已接受。

标签: mysql sql


【解决方案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

【讨论】:

    【解决方案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
    

    只有在满足特定条件时,才可以使用案例求和。

    【讨论】:

      猜你喜欢
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      相关资源
      最近更新 更多