Home > Back-end >  Max Date for each entry
Max Date for each entry

Time:11-05

I'm rather new to SQL and I'm trying to query something that has a lot of duplicates, so I'm getting a lot of dates but I only want 1 of each entry and I'm struggling as to how to do that.

This is an example query of what I have, I'm not sure how to get the result I'm looking for from here though.

select 
    product_id,
    max(date_ordered)
    from products

Update: I've tried Group By as well but there are still duplicate products in the list since there are multiple dates. How do I only list 1 product with the most recent date ordered?

Update: Group by finally ended up working, thanks for those that suggested it. User error.

CodePudding user response:

select product_id,max(date_ordered)
from products
group by product_id

CodePudding user response:

I tried Group by date ordered and products, it still has duplicate products in the list.

Use GROUP BY on the product_id column (and not on the date_ordered column):

SELECT product_id,
       max(date_ordered)
FROM   products
GROUP BY product_id;

CodePudding user response:

You have to use group by ,you have the documentation here : https://sql.sh/cours/group-by

  • Related