如何使用where和Group by返回多个sum的结果

时间:2014-09-22 14:23:52

标签: mysql sql

我正在尝试执行一个查询,在这里我可以根据where子句和group获取一个列的总和,但是它的行为并不像我期望的那样,并且不确定原因。

我有一个交易表:

时间戳( transaction_date
值(金额),
一种类型(payin或支付),
交易前的透明余额(携带),
和期末余额(余额)。

这是我的表的JSON导出:

[
   {
      "id":"2",
      "type":"payout",
      "carry":"2340",
      "amount":"50",
      "balance":"2290",
      "transaction_date":"2014-09-15 00:00:00",
   },
   {
      "id":"1",
      "type":"payin",
      "carry":"340",
      "amount":"2000",
      "balance":"2340",
      "transaction_date":"2014-09-22 09:10:03",
   },
   {
      "id":"3",
      "type":"payout",
      "carry":"0",
      "amount":"50",
      "balance":"0",
      "transaction_date":"2014-09-22 09:10:03",
   },
   {
      "id":"4",
      "type":"payin",
      "carry":"1",
      "amount":"30",
      "balance":"1",
      "transaction_date":"2014-09-22 09:10:03",
   }
] 

我想要实现的是为每个日期(日历日期,而不是时间戳)获取一行,其中包含:
日期(再次是日历而不是时间戳),
在任何交易日之前的初始进行,
该日期的Payins总和,
该日期的支出总额,
当天的最终期末余额。

目前我只收到一个结果,似乎忽略了该组(无论行日期如何,总结所有的支付和所有支出)

SELECT DATE(`transaction_date`) as day, 
SUM(amount) AS pay_in 
FROM transactions 
WHERE type='payin' GROUP BY day

这是我正在使用的完整查询(减去进位和余额)

SELECT payins.day, payins.pay_in, payouts.pay_out 
From
    (SELECT DATE(`transaction_date`) as day, 
     SUM(amount) AS pay_in FROM transactions 
     WHERE type='payin' GROUP BY DATE(`transaction_date`)
     ) payins
LEFT JOIN 
    (SELECT DATE(`transaction_date`) as day, SUM(amount) AS pay_out 
     FROM transactions 
     WHERE type='payout' 
     GROUP BY DATE(`transaction_date`)
     ) payouts 
ON payins.day = payouts.day
Group By day

如果它有任何区别我在OSX 10.9上使用MAMP 3.0.4

1 个答案:

答案 0 :(得分:2)

在这种情况下,您不需要使用子查询,可以将SUMCASE一起使用。此外,你的分组似乎对我来说工作正常,为你的样本数据返回2个结果(参见提供的小提琴):

SELECT Date(transaction_date) date,
    SUM(CASE WHEN type='payin' THEN amount END)) payinsum,
    SUM(CASE WHEN type='payout' THEN amount END) payoutsum
FROM transactions
GROUP BY date