Return one SQL row per product with price and latest date

前端 未结 6 1099
南旧
南旧 2021-01-24 03:35

I am not a SQL guy, I have used it in the past and rarely have an issue that cant be solved by google... however this time I need to ask the Community.

I have a database

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-24 03:59

    You can use a CTE and the ranking function PARTITION BY:

    WITH CTE AS
    (
        select t.ProdNo, t.TransactionDate as 'LastPurchaseDate', t.Price,
               rn = row_number() over (partition by ProdNo order by TransactionDate desc)
        from Transactions t
    )
    SELECT ProdNo, LastPurchaseDate, Price  FROM CTE WHERE RN = 1
    

提交回复
热议问题