我有一个存储客户销售日期的表格如下:
|CustomerId|SalesDate |Product|Price|
|1 |2015-01-01|A | 5.00|
|1 |2015-02-01|A |10.00|
|1 |2015-03-01|B | 7.00|
|2 |2015-01-15|A | 9.00|
我想为购买产品A的每位客户选择一行。如果客户多次购买产品A,我只想查看最近购买的商品。
这是所需的输出:
|CustomerId|SalesDate |Product|Price|
|1 |2015-02-01|A |10.00|
|2 |2015-01-15|A | 9.00|
我已经尝试了不同版本的群组/通过这样的查询:
SELECT CustomerId, SalesDate, Product, Price
FROM Sales
WHERE Product = 'A'
GROUP BY CustomerId
HAVING MAX(SalesDate);
答案 0 :(得分:2)
只需在select语句中获取销售日期的最大值。
select customerid, max(salesdate) as salesdate, 'A'
from sales
where product = 'A'
group by customerid
有新要求
select customerid, maxsalesdate, Product, Price
from sales
join (select customerid, max(salesdate) as maxsalesdate
from sales
where product = 'A'
group by customerid) as sub on
sub.customerid = sales.customerid and
sub.maxsalesdate = sales.salesdate
where product = 'A'
答案 1 :(得分:2)
使用join
和聚合:
select s.*
from sales s join
(select customerid, max(salesdate) as salesdate
from sales s
where product = 'A'
group by customerid
) cs
on s.customerid = cs.customerid and s.salesdate = cs.salesdate
where s.product = 'A';
汇总获取每个客户的最长销售日期。 join
选择与该信息匹配的行。