简体   繁体   中英

SQL Select Distinct using order by and group by in a temp table

I am trying to get the last sale price of all items a customer has sold. The items that I need must only be of a certain category(RENTAL).

The problem that I am running into is that I cant order by date and then select distinct so that it will give me a list of distinct items and their most recent sale price.

I have been messing around with using temp tables that end up looking like this:

Item_Number | Item_Price | Date

Item1 | 29.00 | 2012-08-29 00:00:00.000

Item1 | 20.00 | 2012-08-29 00:00:00.000

Item2 | .35 | 2012-08-29 00:00:00.000

Item1 | 7.00 | 2012-08-27 00:00:00.000

Item2 | 5.00 | 2012-08-27 00:00:00.000

This is a temp table ordered by date then price and then grouped by item number.

What I am trying to do right now is select distinct on item number from this temptable so that it grabs the top item number and price and puts it into a grid. so it would look like this:

Item_Number | Item_Price | Date

Item1 | 29.00 | 2012-08-29 00:00:00.000

Item2 | .35 | 2012-08-29 00:00:00.000

If item2 didnt have a new sale on the 29th it would go to the next latest date and grab the row:

Item2 | 5.00 | 2012-08-27 00:00:00.000

instead of: Item2 | .35 | 2012-08-29 00:00:00.000

I dont know if I am just overthinking this or what but its been giving me trouble for a while now. Any help would be greatly appreciated.

Thanks

Use MAX() to get the last sale price for a given item, and then fetch only rows those rows where their sales date equals the result of MAX() :

SELECT item_number, item_price, date
FROM tbl t
WHERE date = (SELECT MAX(tmp.date)
              FROM tbl tmp
              WHERE tmp.item_number = t.item_number)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM