ここで、問題の簡略化された定義と解決策を確認できます(私が正しく理解している場合): http ://sqlfiddle.com/#!9/48a2e1/1
CREATE TABLE foundry
(
lru varchar(50) NOT NULL,
client int NOT NULL,
purchase_date date,
price int NOT NULL
);
INSERT INTO foundry (lru, client, purchase_date, price) VALUES
("article1", 4001, "01-01-16", 100),
("article1", 4001, "01-01-17", 200),
("article1", 4001, "01-02-16", 300),
("article1", 4001, "01-04-16", 400),
("article1", 4001, "01-06-16", 500),
("article1", 4001, "01-08-16", 600),
("article1", 4001, "01-10-16", 700),
("article1", 4001, "01-11-16", 800),
("article1", 4002, "01-01-16", 900),
("article1", 4002, "01-07-16", 1000),
("article1", 4002, "01-12-16", 1100);
基本的に、lru(記事名)、クライアント、購入日、およびいくつかの価格の4つの列を持つテーブルがあります。
解決策は次のようになります:
SELECT lru, client, avg(price), COUNT(*) as total_items,
MONTHNAME(STR_TO_DATE(L, '%m')) as start_month, MONTHNAME(STR_TO_DATE(R, '%m')) as end_month FROM foundry,
(
SELECT 1 as L, 6 as R
UNION ALL
SELECT 2, 7
UNION ALL
SELECT 3, 8
UNION ALL
SELECT 4, 9
UNION ALL
SELECT 5, 10
UNION ALL
SELECT 6, 11
UNION ALL
SELECT 7, 12
) months
WHERE month(purchase_date) >= L AND month(purchase_date) <= R
GROUP BY lru, client, L, R
アイデアは次のとおりです。
- 月の可能なすべての組み合わせを生成します:1-6、2-7、...、7,12
- 生成された月の組み合わせでソースデータを結合する
- GROUPBYでAVGを使用する
そしてその結果:
lru client avg(price) total_items start_month end_month
article1 4001 300 5 January June
article1 4001 400 3 February July
article1 4001 500 3 March August
article1 4001 500 3 April September
article1 4001 600 3 May October
article1 4001 650 4 June November
article1 4001 700 3 July December
article1 4002 900 1 January June
article1 4002 1000 1 February July
article1 4002 1000 1 March August
article1 4002 1000 1 April September
article1 4002 1000 1 May October
article1 4002 1000 1 June November
article1 4002 1050 2 July December