输入
表1:标题
ID ITEMNAME COST
1 MIXEE 1800
2 REFRIZIRATOR 12000
表2:DETAILS
DID DITEMNAME DLINE DCOST
1 MIXEE 1 900
2 MIXEE 2 900
3 REFRIGIRATOR 1 9000
4 REFRIGIRATOR 2 1000
预期OutPut
DETAILS
DID DITEMNAME DLINE DCOST
1 MIXEE 1 900
2 MIXEE 2 900
3 REFRIGIRATOR 1 12000
4 REFRIGIRATOR 2 0
说明:标题表将包含摘要总和或行级信息,或者它包含准确的信息和详细信息表可能不包含准确的信息成本
因此,如果标头表成本和详细信息表成本之和相同,那么我需要保留记录,因为它是其他方面我需要使第一行级别值是标头表的成本,下一行应该为零。
像这样,我在详细信息表中有大约80个lacs记录。
答案 0 :(得分:0)
好的,所以我想我明白了。如果需要任何调整,请告诉我。
DECLARE @Header TABLE (ID INT, ItemName VARCHAR(20), Cost INT);
DECLARE @Details TABLE (ID INT, DiteName VARCHAR(20), Dline TINYINT,DCost INT);
INSERT INTO @Header
VALUES (1,'Mixee',1800),
(2,'Refridgerator',12000);
INSERT INTO @Details
VALUES (1,'Mixee',1,900),
(2,'Mixee',2,900),
(3,'Refridgerator',1,9000),
(4,'Refridgerator',2,9000);
SELECT D.ID,
D.DiteName,
D.Dline,
CASE
WHEN H.Cost = sum_DCost THEN DCost
ELSE CASE
WHEN D.ID = CA.min_ID THEN H.Cost
ELSE 0
END
END AS DCost
FROM @Details AS D
CROSS APPLY (
SELECT DiteName,SUM(DCost) sum_DCost,MIN(ID) min_ID
FROM @Details
WHERE DiteName = D.DiteName
GROUP BY DiteName
) CA
INNER JOIN @Header AS H
ON D.DiteName = H.ItemName
答案 1 :(得分:0)
以下是如何做到这一点:
SELECT d.ID, d.DITEMNAME, d.DLINE,
CASE WHEN SUM(d.DCOST) OVER(PARTITION BY d.DITEMNAME) = h.COST
THEN d.DCOST
ELSE CASE WHEN d.DLINE = 1 THEN h.COST ELSE 0 END END AS DCOST
FROM Header h
JOIN Details d ON h.ITEMNAME = d.DITEMNAME