1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
-- Commençons par nos données...
DECLARE @TABLE TABLE (MAR_ID INT, SEL_ID INT, COL_A INT, COL_B INT)
INSERT INTO @TABLE SELECT 1234, 987, 2, -4
INSERT INTO @TABLE SELECT 1234, 786, -5, 6
INSERT INTO @TABLE SELECT 1234, 654, 10, -7
INSERT INTO @TABLE SELECT 3333, 0, 333, -666
INSERT INTO @TABLE SELECT 4444, 0, 444, -666
-- En assumant que SEL_ID soit unique
DECLARE @SEL_ID INT
SET @SEL_ID = 786;
WITH MAR_CTE (MAR_ID) AS (SELECT MAR_ID FROM @TABLE WHERE SEL_ID = @SEL_ID),
COL_A_CTE (TOTAL) AS (SELECT COL_A AS TOTAL FROM @TABLE WHERE SEL_ID = @SEL_ID),
COL_B_CTE (TOTAL) AS (SELECT SUM(COL_B) AS TOTAL FROM @TABLE WHERE SEL_ID <> @SEL_ID AND MAR_ID = (SELECT MAR_ID FROM MAR_CTE))
SELECT SUM(TOTAL) AS TOTAL
FROM (
SELECT TOTAL
FROM COL_A_CTE
UNION ALL
SELECT TOTAL
FROM COL_B_CTE
) TOTALS
-- 987 = 1
-- 786 = -16 |
Partager