1

我有 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

我怎样才能做到这一点?或者你能推荐我更好的桌子设计吗?

4

1 回答 1

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`
于 2012-11-26T15:21:32.170 回答