Return one SQL row per product with price and latest date

前端 未结 6 1192
南旧
南旧 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 04:13

    You're on the right track. What if you use:

    select t.ProdNo, t.TransactionDate as 'LastPurchaseDate', t.Price
    from Transactions t
    inner join (
         select ProdNo, max(TransactionDate) as 'LastPurchaseDate'
         from Transactions
         WHERE Price > 0
         group by ProdNo
     ) tm on t.ProdNo = tm.ProdNo and t.TransactionDate= tm.LastPurchaseDate
    

    Note the change in join conditions.

    What happened in your query: LastPurchaseDate = tm.LastPurchaseDate. There is only one column called LastPurchaseDate, so it's equating it with itself, which is always true. So you're left with t.ProdNo = tm.ProdNo, since t.ProdNo is not unique, you get multiple records returned for each t.ProdNo.

提交回复
热议问题