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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| DECLARE @T1 TABLE
(
Caisse INT NOT NULL,
NomCaisse VARCHAR(20) NOT NULL
);
DECLARE @T2 TABLE
(
Outils VARCHAR(20) NOT NULL,
Caisse INT NOT NULL
);
INSERT INTO @T1 VALUES (1,'Caisse1');
INSERT INTO @T1 VALUES (2,'Caisse2');
INSERT INTO @T2 VALUES ('marteau',1);
INSERT INTO @T2 VALUES ('marteau',1);
INSERT INTO @T2 VALUES ('marteau',1);
INSERT INTO @T2 VALUES ('Pince',1);
INSERT INTO @T2 VALUES ('Tournevis',1);
INSERT INTO @T2 VALUES ('Tournevis',1);
INSERT INTO @T2 VALUES ('Scie',1);
INSERT INTO @T2 VALUES ('Perceuse',1);
INSERT INTO @T2 VALUES ('Perceuse',1);
INSERT INTO @T2 VALUES ('Perceuse',1);
INSERT INTO @T2 VALUES ('Perceuse',1);
INSERT INTO @T2 VALUES ('marteau',2);
INSERT INTO @T2 VALUES ('marteau',2);
INSERT INTO @T2 VALUES ('Pince',2);
INSERT INTO @T2 VALUES ('Pince',2);
INSERT INTO @T2 VALUES ('Tournevis',2);
INSERT INTO @T2 VALUES ('Tournevis',2);
INSERT INTO @T2 VALUES ('Scie',2);
INSERT INTO @T2 VALUES ('Scie',2);
INSERT INTO @T2 VALUES ('Perceuse',2);
INSERT INTO @T2 VALUES ('Perceuse',2);
-- Solution avec CASE
SELECT
t1.caisse,
COALESCE(SUM(CASE WHEN t2.Outils = 'marteau' THEN 1 ELSE 0 END),0) AS marteau,
COALESCE(SUM(CASE WHEN t2.Outils = 'Pince' THEN 1 ELSE 0 END),0) AS Pince,
COALESCE(SUM(CASE WHEN t2.Outils = 'Tournevis' THEN 1 ELSE 0 END),0) AS Tournevis,
COALESCE(SUM(CASE WHEN t2.Outils = 'Scie' THEN 1 ELSE 0 END),0) AS Scie,
COALESCE(SUM(CASE WHEN t2.Outils = 'Perceuse' THEN 1 ELSE 0 END),0) AS Perceuse
FROM @t1 t1
INNER JOIN @t2 t2
ON t1.Caisse = t2.Caisse
GROUP BY t1.caisse;
-- Solution avec PIVOT
SELECT *
FROM
(
SELECT
t1.Caisse,
t2.Outils
FROM @t1 t1
INNER JOIN @t2 t2
ON t1.Caisse = t2.Caisse
) AS p
PIVOT
(
COUNT(Outils)
FOR Outils IN ([marteau],[Pince],[Tournevis],[Scie],[Perceuse])
) AS r
; |
Partager