sql group by function

后端 未结 3 1427
误落风尘
误落风尘 2021-01-28 09:45

I need to only get the line with the highest transactiontime per productId. So In this case I need to get the first line and all the other lines with productid 224 should be gon

3条回答
  •  花落未央
    2021-01-28 10:16

    As you said, grouping by NQ is what's messing your result up, because each row has a different value.

    If you can assume that latest TransactionTime has lowest NQ value (which is true with the sample data you provided) you can just remove NQ from the group by and select min(NQ) instead of plain NQ.

    SELECT  min(NQ), ProductId, Product, Warehouse, ProductType, MAX(Transactiontime) as 'TransactionTime'
    FROM    @MaxTime
    GROUP BY Productid, Product, Warehouse, ProductType 
    ORDER BY ProductId
    

    I'm afraid that would be assuming too much, and if that's true you will have to use @HoneyBadger answer

提交回复
热议问题