アプリの事前レポートを作成しようとしています。そして今、私はいくつかのクエリで問題に直面しています。
詳細は次のとおりです。
テーブル製品
id | name
-----+---------
1 | Book
2 | Pen
3 | Ruler
4 | Calendar
5 | Scissors
テーブルイベント
id | name
-----+---------
1 | Launching
2 | Sale
3 | Roadshow
4 | Presentation
5 | Normal
table_transaction
---+------------+-------+-----------+---------+-----------+---------+-----------+---------+----------+
id | date | event | product_1 | share_1 | product_2 | share_2 | product_3 | share_3 | amount |
---+------------+-------+-----------+---------+-----------+---------+-----------+---------+----------+
1 | 2013-01-12 | 1 | 3 | 50 | 2 | 50 | | | 5000 |
2 | 2013-02-13 | 3 | 2 | 50 | 1 | 25 | 4 | 25 | 10000 |
3 | 2013-01-13 | 5 | 5 | 50 | 4 | 50 | | | 7000 |
4 | 2013-04-13 | 2 | 1 | 100 | | | | | 5000 |
---+------------+-------+-----------+---------+-----------+---------+-----------+---------+----------+
表示したいのはこんな感じ
--------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
Product Name | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec |
--------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
Book | | 2500 | | 5000 | | | | | | | | |
Pen | 2500 | 5000 | | | | | | | | | | |
Ruler | 2500 | | | | | | | | | | | |
Calendar | 3500 | 2500 | | | | | | | | | | |
Scissors | 3500 | | | | | | | | | | | |
--------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
私が試したこと: 次のクエリを使用して、イベント名のグループ化の出力を正常に生成します
SELECT t1.name as sort_name,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 1, t2.amount, 0)) as total_jan,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 2, t2.amount, 0)) as total_feb,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 3, t2.amount, 0)) as total_mar,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 4, t2.amount, 0)) as total_apr,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 5, t2.amount, 0)) as total_may,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 6, t2.amount, 0)) as total_jun,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 7, t2.amount, 0)) as total_jul,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 8, t2.amount, 0)) as total_aug,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 9, t2.amount, 0)) as total_sep,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 10, t2.amount, 0)) as total_oct,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 11, t2.amount, 0)) as total_nov,
sum(IF(YEAR(t2.date) = 2013 AND MONTH(t2.date) = 12, t2.amount, 0)) as total_dec,
sum(IF(YEAR(t2.date) = 2013, t2.amount, 0)) as event_total
FROM events t1
LEFT JOIN transactions t2 ON t2.event_id = t1.id
GROUP BY sort_name
しかし、製品ごとにグループ化する考えはありません。ユニオンで遊んでみましたが、それでも SQL 構文エラーが返されます。