Sql 从同一表中查找不匹配ID的总和
例如,我在下表Sql 从同一表中查找不匹配ID的总和,sql,sql-server,tsql,Sql,Sql Server,Tsql,例如,我在下表 ID DetailedID ReferenceID ItemID Qty 01 101 80 A101 100 01 102 90 A102 200 01 103 0 A101 050 01 104 0 A109 1
ID DetailedID ReferenceID ItemID Qty
01 101 80 A101 100
01 102 90 A102 200
01 103 0 A101 050
01 104 0 A109 100
02 105 81 1010 100
02 106 82 1010 100
03 107 0 1111 020
03 108 81 1010 100
03 109 0 X200 010
03 110 0 1010 020
现在,我需要ReferenceID=0和ItemID不匹配的数量之和,根据ID-wise,我将显示该数量之和,以添加一列和该ID的detaileId的最小值
我想要输出像
ID DetailedID ReferenceID ItemID Qty AddQty
01 101 80 A101 100 055
01 102 90 A102 200 NULL
01 103 0 A101 050 NULL
01 104 0 A109 055 NULL
02 105 81 1010 100 NULL
02 106 82 1010 100 NULL
03 107 0 1111 020 030
03 108 81 1010 100 NULL
03 109 0 X200 010 NULL
03 110 0 1010 020 NULL
您可以尝试以下方法:
DECLARE @DataSource TABLE
(
[ID] TINYINT
,[DetailedID] TINYINT
,[ReferenceID] TINYINT
,[ItemID] VARCHAR(12)
,[Qty] TINYINT
);
INSERT INTO @DataSource ([ID], [DetailedID], [ReferenceID], [ItemID], [Qty])
VALUES (01, 101, 80, 'A101', 100)
,(01, 102, 90, 'A102', 200)
,(01, 103, 0, 'A101', 50)
,(01, 104, 0, 'A109', 55)
,(02, 105, 81, '1010', 100)
,(02, 106, 82, '1010', 100)
,(03, 107, 0, '1111', 20)
,(03, 108, 81, '1010', 100)
,(03, 109, 0, 'X200', 10)
,(03, 110, 0, '1010', 20);
WITH DataSource AS
(
SELECT DS.[ID]
,SUM(DS.[Qty]) AS [AddQty]
FROM @DataSource DS
WHERE DS.[ReferenceID] = 0
AND NOT EXISTS(SELECT 1 FROM @DataSource I WHERE I.[ItemID] = DS.[ItemID] AND I.[ReferenceID] <> 0)
GROUP BY DS.[ID]
), DataSourceWithMinDetailedID AS
(
SELECT [ID]
,MIN([DetailedID]) AS [MinDetailedID]
FROM @DataSource
GROUP BY [ID]
)
SELECT A.*
,C.[AddQty]
FROM @DataSource A
LEFT JOIN DataSourceWithMinDetailedID B
ON A.[ID] = B.[ID]
LEFT JOIN DataSource C
ON B.[ID] = C.[ID]
AND A.[DetailedID] = B.[MinDetailedID];
请检查以下内容
您将认识到,除了使用CASE语句外,我还使用了带有partitionby子句的和聚合函数
我希望这是清楚的
/*
create table ItemQuantity (
ID varchar(2),
DetailedID int,
ReferenceID int,
ItemID varchar(5),
Qty int)
insert into ItemQuantity values
('01', 101, 80 ,'A101', 100),
('01', 102, 90 ,'A102', 200),
('01', 103, 0 ,'A101', 050),
('01', 104, 0 ,'A109', 100),
('02', 105, 81 ,'1010', 100),
('02', 106 , 82 ,'1010', 100),
('03', 107 , 0 ,'1111', 020),
('03', 108 , 81 ,'1010', 100),
('03', 109 , 0 ,'X200', 010),
('03', 110 , 0 ,'1010', 020)
*/
;with cte as (
select
* ,
QtyTemp = case when ReferenceID = 0 then Qty else 0 end,
Flag = case when exists(select * from ItemQuantity k where i.ItemID = k.ItemID and k.ReferenceID <> 0) then 1 else 0 end,
rn = row_number() over (partition by ID order by DetailedID)
from ItemQuantity i
)
select ID, DetailedID, ReferenceID, ItemID, Qty,
AddQty = case when rn = 1 then SUM(case when ReferenceID = 0 and Flag = 0 then QtyTemp else 0 end) OVER (Partition By ID) else null end
from cte
关于您的样本,您在所需输出的一行中有55个作为数量。但该行的样本数据有100个。请根据这一点检查数据和输出
我的脚本执行以下输出
我希望这会有所帮助,您能显示您尝试过的查询吗?第一行的055在哪里。试图理解逻辑