假设我有一个这样的表:
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)
我的结果应该是:
customer | sales | 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 fiddle
答案 0 :(得分:3)
试试这个
SELECT a.customer, count(a.sale), max_sale
FROM sales a
INNER JOIN (SELECT customer, sale max_sale
from sales x where dates = (select max(dates)
from sales y
where x.customer = y.customer
and y.sale > 0
)
)b
ON a.customer = b.customer
GROUP BY a.customer, max_sale;
答案 1 :(得分:1)
SELECT a.customer,
COUNT(a.sale) total_sales,
c.sale
FROM sales a
INNER JOIN
(
SELECT a.*
FROM sales a
INNER JOIN
(
SELECT Customer, MAX(Dates) max_date
FROM sales
WHERE sale > 0
GROUP BY Customer
) b ON a.customer = b.customer AND
a.dates = b.max_date
) c ON a.customer = c.customer
GROUP BY a.customer, c.sale