次のようなテーブルがあるとします。
ID | 日付 | 顧客 | セール
そして、顧客ごとに次を選択します。
- 購入数
- 前回の購入額
- 正の値の場合の合計購入金額
このテーブル定義では:
CREATE TABLE sales (
id int auto_increment primary key,
dates date,
customer int,
sale int
);
そして、このデータ:
INSERT INTO sales
(dates, customer, sale)
VALUES
('2012-01-01', 1, 2),
('2012-02-01', 1, 8),
('2012-03-01', 2, 1),
('2012-04-01', 2, 7),
('2012-05-01', 2, -5),
('2012-06-01', 1, 5)
私の結果は次のようになります。
顧客 | 販売 | last_sale 1 3 5 2 3 7
入手方法がわかりません。私はこれに達しました:
SELECT s.customer, COUNT(s.sale) total_sales, last_sale FROM sales AS s
JOIN
(SELECT customer, sale last_sale FROM sales GROUP BY customer ORDER BY dates DESC) AS t
ON t.customer=s.customer
GROUP BY s.customer
しかし、それは機能していません。このデータを取得する方法のアイデアはありますか?
すべてのコードはSQL フィドルにあります