显示基于另一行值的金额总和

时间:2012-11-26 15:15:23

标签: php mysql sql database

我有SQL表:

id_details
year-month
type (only have 2 values , income and outcome)
amount

和表格有这样的行:

(year-month)      (type)     (amount)
 November-2012    income      50000
 November-2012    income      30000
 December-2012    income      20000
 November-2012    outcome     10000
 December-2012    outcome     50000
 December-2012    income      10000

我想要的是,显示一个结果如下的查询:

 (year-month)    (sum income)     (sum-outcome)   (sub-total balance)
 November-2012    80000             10000          70000
 December-2012    30000             50000          -20000 

最后

  total-balance = 50000

我该怎么做? 或者你能推荐我更好的桌子设计吗?

1 个答案:

答案 0 :(得分:1)

SELECT `year-month`,
       SUM(CASE WHEN type = 'income' THEN amount ELSE 0 END) `sum-income`,
       SUM(CASE WHEN type = 'outcome' THEN amount  ELSE 0 END) `sum-outcome`,
       SUM(amount) `sum-total balance`
FROM <JOINS>
GROUP BY `year-month`