I have a table that stores customer sales date like this:
|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|
I'd like to select a single row for each customer who has purchased product A. If a customer has purchased product A more than once, I'd like to only see the most recent purchase.
This is the desired output:
|CustomerId|SalesDate |Product|Price|
|1 |2015-02-01|A |10.00|
|2 |2015-01-15|A | 9.00|
I've tried different versions of a group by/having queries like this:
SELECT CustomerId, SalesDate, Product, Price
FROM Sales
WHERE Product = 'A'
GROUP BY CustomerId
HAVING MAX(SalesDate);
Just grab the max of sales date in the select statement.
select customerid, max(salesdate) as salesdate, 'A'
from sales
where product = 'A'
group by customerid
with new requirements
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'
Do this using a join
and aggregation:
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';
The aggregation gets the maximum sales date for each customer. The join
selects the row that matches that information.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.