sql group by function

时间:2017-05-31 08:46:47

标签: sql sql-server tsql

我只需要获得每个productId具有最高事务处理时间的行。因此,在这种情况下,我需要获得第一行,所有其他行与productid 224应该消失。我怎样才能解决这个问题?现在我按NQ分组,但有多行,因为NQ会因每次交易而改变。我也不能拿SUM,因为它会加起来而不是在某个交易时间拿NQ。非常感谢帮助

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

Results

3 个答案:

答案 0 :(得分:1)

你可以这样做:

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

答案 1 :(得分:0)

正如您所说,按NQ进行分组会使您的结果变得混乱,因为每行都有不同的值。

如果您认为最新的TransactionTime具有最低NQ值(对于您提供的示例数据都是如此),您只需从NQ移除group by即可选择min(NQ)而不是普通NQ

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

我担心会假设太多,如果这是真的,你将不得不使用@HoneyBadger回答

答案 2 :(得分:0)

您可以使用CTE,以确保从与NQ相同的行中获取TransactionTime,例如:

;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