表:会计
date_due date_paid amount_due amount_paid category_type
2012-08-12 2012-08-12 500 450 Income
2012-08-13 2012-08-17 200 300 Expense
2012-09-15 2012-09-13 300 300 Income
2012-09-17 2012-09-16 100 100 Income
Run Code Online (Sandbox Code Playgroud)
如何生成表格如下:
date_paid IncomeAmountPaid ExpenseAmountPaid
2012-08 TOTAL INCOME IN AUGUST TOTAL EXPENSE IN AUGUST
2012-09 TOTAL INCOME IN SEPT. TOTAL EXPENSE IN SEPTEMBER
Run Code Online (Sandbox Code Playgroud)
您可以使用以下实现CASE语句和GROUP BY:
select date_format(date_paid, '%Y-%m') date_paid,
sum(case when category_type = 'Income' then amount_paid end) IncomePaid,
sum(case when category_type = 'Expense' then amount_paid end) ExpensePaid
from accounting
group by date_format(date_paid, '%Y-%m')
Run Code Online (Sandbox Code Playgroud)