New to SQL. Can someone please tell me if my SQL query is correct? I am trying to find out how much each unique customer spent on their most recent transaction.
Table Name: Expenditure
Columns:
1. created_time
2. customer_id
3. spend
SELECT
distinct(customer_id), sum(spend)
FROM
Expenditure
WHERE
created_time =
(SELECT MAX(created_time))
FROM
Expenditure
GROUP BY
distinct(customer_id)
If you are using MySQL 8+, then I prefer to use window functions here:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_time DESC) rn
FROM Expenditure
)
SELECT customer_id, created_time, spend
FROM cte
WHERE rn = 1;
To correct the approach you were trying to use, you can correlate the subquery to the outer query by customer:
SELECT customer_id, created_time, spend
FROM expenditure e1
WHERE created_time = (SELECT MAX(e2.created_time)
FROM Expenditure
WHERE e2.customer_id = e1.customer_id);
If your using mysql 5.7 below. you might want to try this query.
select distinct(t1.customer_id), sum(t1.spend)
from Expenditure t1
inner join
(select max(created_time) as created_time, customer_id)
from Expenditure
group by distinct(customer_id) t2 on t2.customer_id = t1.customer_id and t2.created_time = t1.created_time
group by
distinct(t1.customer_id)
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.