找出仓库中占用最多space的商品类型

Find the type of goods that takes up the most space in the warehouse

我有这样的查询

select StockId, ProductType, sum(ProductVolume) as ProductTypeVolume
from myTable
where InStock = 1
group by StockId, ProductType

结果是这样的

StockId ProductType ProductTypeVolume
10 Type1 65
10 Type2 25
10 Type3 45
20 Type2 80
20 Type4 60
20 Type5 20

我需要得到一个结果,其中有两行,每个 StockId,具有最大的 ProductTypeVolume,如下所示

StockId ProductType ProductTypeVolume
10 Type1 65
20 Type2 80

您需要 CTEsubquerygroup by

WITH t
     AS (SELECT stockid,
                producttype,
                Sum(productvolume) AS ProductTypeVolume
         FROM   mytable
         WHERE  instock = 1
         GROUP  BY stockid,
                   producttype)


SELECT A.stockid,
       B.producttype,
       A.producttypevolume
FROM   (SELECT stockid,
               Max(producttypevolume) ProductTypeVolume
        FROM   t
        GROUP  BY stockid) A
       JOIN t B
         ON A.stockid = B.stockid
            AND A.producttypevolume = B.producttypevolume  

您可以使用row_number如下

SELECT TOP(2) stockid,
              producttype,
              producttypevolume
--,ROW_NUMBER() OVER (PARTITION BY StockId ORDER BY ProductTypeVolume DESC)
FROM   t
ORDER  BY Row_number()
            OVER (
              partition BY stockid
              ORDER BY producttypevolume DESC) ASC