sql group by function

后端 未结 3 1398
误落风尘
误落风尘 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 do:

    SELECT  MT.NQ, MT.ProductId, MT.Product, MT.Warehouse, MT.ProductType, MT.Transactiontime
    FROM    @MaxTime MT
    INNER JOIN (
                    SELECT  ProductId
                    ,       MAX(Transactiontime) AS 'TransactionTime'
                    FROM    @MaxTime
                    GROUP BY Productid
                ) GR
            ON  MT.ProductId = GR.ProductId
            AND MT.TransactionTime = GR.TransactionTime
    ORDER BY MT.ProductId
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题