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
|
create table t_client
(
id int identity not null primary key,
code_cli varchar(10) not null
);
create table t_commande
(
id int identity not null primary key,
id_clt int not null references t_client(id),
code_com varchar(10) not null
);
insert into t_client (code_cli) values
('Client 1'),
('Client 2'),
('Client 3'),
('Client 4'),
('Client 5');
insert into t_commande (id_clt, code_com) values
(1, 'Clavier'), (1, 'Souris'), (1, 'Ecran'), (1, 'Clavier'), (1, 'Souris'),
(2, 'Clavier'), (2, 'Souris'), (2, 'Clavier'),
(3, 'Clavier'), (3, 'Clavier'),
(4, 'Ecran'), (4, 'Clavier'),
(5, 'Souris'), (5, 'Clavier');
-- Première proposition de StringBuilder
SELECT C.ID
FROM T_CLIENT AS C
INNER JOIN T_COMMANDE AS M
ON C.ID = M.id_clt
GROUP BY C.ID
HAVING sum(case code_com when 'Clavier' then 0 when 'Souris' then 0 else 1 end) = 0 AND count(DISTINCT code_com) = 2;
-- Première proposition de Fred_34
SELECT C.ID
FROM T_CLIENT AS C
INNER JOIN T_COMMANDE AS M
ON C.ID = M.id_clt
WHERE M.code_com IN ('Souris', 'Clavier')
AND (SELECT COUNT(DISTINCT code_com)
FROM T_COMMANDE AS CD
WHERE CD.id_clt = C.ID) = 2
GROUP BY C.ID
HAVING COUNT(DISTINCT code_com)=2;
-- Seconde proposition de StringBuilder
SELECT c.id
FROM t_client c
INNER JOIN t_commande m ON m.id_clt = c.id AND m.code_com IN ('Souris', 'Clavier')
WHERE NOT EXISTS (SELECT NULL FROM t_commande z WHERE z.id_clt = c.id AND z.code_com NOT IN ('Souris', 'Clavier'))
GROUP BY c.id
HAVING count(DISTINCT m.code_com) = 2; |
Partager