SQL Server 2008 - 条件匹配时合并行

时间:2017-10-02 14:42:42

标签: sql-server sql-server-2008

我正在运行存储过程并获得以下值。

Name    ID   NewID  Qty     Rqty    Total
Test1   1            5       4        9
Test2   10   1001    3       0        3
Test2   1001         4       2        6
Test3   15   1005    0       0        0
Test3   1005         3       4        7

如果您查看Test3,其中第一个标识15的新标识为1005,但QtyRqty0,下一行我收到了ID 1005Qty, Rqty 3以及4,总计7,这是正确的。

我想要做的是当任何ID获得新ID而Qty, Rqty都是0时,我需要在行中输出以下内容

Test3   15  1005    3   4   7

所以,我的最终结果将是 -

Name    ID   NewID   Qty    Rqty  Total
Test1   1             5      4      9
Test2   10   1001     3      0      3
Test2   1001          4      2      6
Test3   15   1005     3      4      7

我的存储过程是 -

select Name, ID, NewID, Qty, RQty, SUM(Qty + RQty) as Total  
from table1
Group By Name, ID, NewID, Qty, RQty
Order by Name

请有人帮忙解决这个问题。

由于

1 个答案:

答案 0 :(得分:2)

您需要根据条件生成伪“分组”ID和NewID,在这些字段上分组并选择原始ID和NewID的MIN和MAX以及其他值的聚合。 e.g。

CREATE TABLE dbo.Tests
(
    Name    varchar(10),    
    ID      int,
    [NewID] int NULL,
    Qty     int,
    Rqty    int
);
INSERT dbo.Tests (Name,ID,[NewID],Qty,Rqty)
--VALUES ('Test1',1,NULL,5,4)
--    ,('Test2',10,1001,3,0)
--    ,('Test2',1001,NULL,4,2)
--    ,('Test3',15,1005,0,0)
--    ,('Test3',1005,NULL,3,4);
VALUES ('test1',1,101,0,0)
      ,('test1',101,NULL,2,4)
      ,('test2',2,102,0,0) 
      ,('test2',102,NULL,4,5) 
      ,('test3',3,103,0,0) 
      ,('test3',103,NULL,3,3) 
      ,('test4',4,104,0,0) 
      ,('test4',104,NULL,1,3) 
      ,('test5',5,105,0,0) 
      ,('test5',105,NULL,3,6);

SELECT t.Name,
       min(t.ID) AS ID,
       max(t.[NewID]) AS [NewID],
       sum(t.Qty) AS Qty,
       sum(t.Rqty) AS Rqty,
       sum(t.Qty)+sum(t.Rqty) AS Total
FROM dbo.Tests AS t
CROSS APPLY (VALUES(CASE WHEN Qty = 0 AND Rqty = 0 AND t.[NewID] IS NOT NULL THEN [NewID] ELSE ID END,
                    CASE WHEN Qty = 0 AND Rqty = 0 AND t.[NewID] IS NOT NULL THEN -1 ELSE coalesce([NewID],-1) END)
            ) x(GroupingID, GroupingNewID)
GROUP BY Name,x.GroupingID,x.GroupingNewID
ORDER BY Name,max(t.ID);

Results of above query