基于字段分组的MAX数量和SUM数量的SELECT ROW

时间:2018-11-13 20:55:03

标签: sql-server group-by

我正在尝试对数量行进行求和并按零件号和装箱进行分组,然后选择开始时具有最大数量的装箱。在下面的查询中,仅选择bin 1-B。我的结果集应针对1-2345部分:Bin 1-A,Sum of bins = 150,该容器中的总数= 100

CREATE TABLE inventory (
ID int IDENTITY(1,1) PRIMARY KEY,
bin nvarchar(25),
partnumber nvarchar(25),
qty int
);

INSERT INTO inventory ( bin, partnumber, qty)
VALUES ('1-A', '1-2345', '100'), ('1-A', '1-2347', '10'), ('1-A', '1-2348', 
'15'), ('1-B', '1-2345', '50'), ('1-B', '1-2347', '50'), ('1-B', '1-2348', 
'55')

;With cte as
    ( SELECT bin, partnumber, sum(qty) qty
    , ROW_NUMBER() OVER( Partition By  partnumber ORDER BY bin desc) as rn 
from inventory
     GROUP BY bin, partnumber) 
SELECT * FROM cte where rn = 1 

结果集应为
输出:

bin partnumber  sum_of_bins max_qty_in_bin  
1-A 1-2345      150         100             
1-B 1-2347      60          50              
1-B 1-2348      70          55  

2 个答案:

答案 0 :(得分:1)

旋转一下:

DECLARE @inventory TABLE (ID int IDENTITY(1,1), bin nvarchar(25), partnumber nvarchar(25), qty int);

INSERT INTO @inventory ( bin, partnumber, qty)
VALUES ('1-A', '1-2345', '100'), ('1-A', '1-2347', '10'), ('1-A', '1-2348','15'), ('1-B', '1-2345', '50'), ('1-B', '1-2347', '50'), ('1-B', '1-2348', '55')

;WITH CTE AS
    ( 
        SELECT bin, partnumber
                , sum(qty) OVER(Partition By partnumber) AS sum_of_bins
                , max(qty) OVER(Partition By partnumber) AS max_qty_in_bin
                , ROW_NUMBER() OVER(Partition By partnumber ORDER BY qty desc) as rn 
        FROM @inventory
        GROUP BY bin, partnumber, qty) 

SELECT * 
FROM cte
WHERE rn=1

输出:

bin partnumber  sum_of_bins max_qty_in_bin  rn
1-A 1-2345      150         100             1
1-B 1-2347      60          50              1
1-B 1-2348      70          55              1

答案 1 :(得分:1)

由于您没有提供示例输出,因此您不清楚要做什么。从您的最后一句话:

With cte as
( SELECT bin, partnumber, 
      sum(qty) over (Partition By  partnumber) as sumQty,
      sum(qty) over (Partition By  partnumber Order by bin) as totQty,
     ROW_NUMBER() OVER ( Partition By  partnumber ORDER BY bin) as rn 
from inventory
) 
SELECT * FROM cte where rn = 1; 

这里是DBFiddle Demo.