sql group by function

后端 未结 3 1428
误落风尘
误落风尘 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 09:55

    You could use a CTE, so that you ensure you get the NQ from the same row as the TransactionTime, e.g.:

    ;WITH Data AS (
        SELECT      NQ, 
                    ProductId, 
                    Product, 
                    Warehouse, 
                    ProductType, 
                    TransactionTime,
                    ROW_NUMBER() OVER (PARTITION BY Productid, Product, Warehouse, ProductType ORDER BY TransactionTime DESC) AS rn
    
        FROM        @MaxTime
    )
    SELECT      NQ, 
                ProductId, 
                Product, 
                Warehouse, 
                ProductType, 
                TransactionTime
    
    FROM        Data
    
    WHERE       rn = 1
    
    ORDER BY    ProductId
    

提交回复
热议问题