1

表: アカウンティング

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

次のようなテーブルを生成するにはどうすればよいですか:

date_paid       IncomeAmountPaid               ExpenseAmountPaid
2012-08         TOTAL INCOME IN AUGUST         TOTAL EXPENSE IN AUGUST
2012-09         TOTAL INCOME IN SEPT.          TOTAL EXPENSE IN SEPTEMBER
4

3 に答える 3

5

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')

デモで SQL Fiddle を参照してください

于 2012-09-26T15:52:28.993 に答える
0

グループ化する方法

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name 

合計する方法

SELECT SUM(column_name) FROM table_name

分割する方法

分割関数を作成する

CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');

次に、関数を使用します

SELECT SPLIT_STR(string, delimiter, position)
于 2012-09-26T15:46:30.613 に答える
0

あなたはこれを試すことができます、

 select Year(date_paid), Month(date_paid),
  sum(case when category_type = 'Income' then amount_paid end) IncomeAmountPaid,
  sum(case when category_type = 'Expense' then amount_paid end) ExpenseAmountPaid
 group by Year(date_paid), Month(date_paid)
于 2012-09-26T15:59:13.887 に答える