专属条款

时间:2014-11-04 09:59:17

标签: tsql where-clause

我试图获得一个结果,其中只有汽车: 选择翼,门和挡风玻璃。

只有那些只有这三个部分的汽车。

我似乎无法使where子句正确,这就是我所拥有的:

CREATE TABLE Cars (
NameID int Identity(1,1) NOT NULL,
CarMake varchar(20) NOT NULL,
CarPart varchar(10) NOT NULL)

数据

INSERT INTO Cars (CarMake, CarPart)
VALUES  
('FIAT' ,'Wing'),
('FIAT' ,'Door'),
('FIAT' ,'windscreen'),
('FORD' ,'Wing'),
('FORD' ,'Door'),
('FORD' ,'windscreen'),
('FORD' ,'Seat'),
('FORD' ,'Bumper'),
('MINI' ,'Windscreen'),
('MINI' ,'door'),
('RENUALT'  ,'Door'),
('RENUALT'  ,'Seat'),
('RENUALT'  ,'Wing'),
('VOLVO'    ,'wing'),
('VOLVO'    ,'door'),
('VOLVO'    ,'bonnet'),
('VOLVO'    ,'windscreen'),
('VOLVO'    ,'bumper'),
('VOLVO'    ,'seat')

声明

SELECT CarMake
FROM Car_CTE
WHERE CarPart = 'Wing' AND CarPart = 'Door' AND CarPart =  'Windscreen'
GROUP BY CarMake;
GO

2 个答案:

答案 0 :(得分:0)

仅选择仅包含3个carparts的组

SELECT CarMake
FROM Car_CTE
GROUP BY CarMake
HAVING sum(case when CarPart IN ('Wing', 'Door', 'windscreen') then 1 else 0 end) = 3
AND sum(case when CarPart NOT IN ('Wing', 'Door', 'windscreen') then 1 else 0 end) = 0

为了得到那些没有这些部分的人

SELECT CarMake
FROM Car_CTE 
GROUP BY CarMake
HAVING sum(case when CarPart IN ('Wing', 'Door', 'Windscreen') then 1 else 0 end) = 0

SQLFiddle demo

答案 1 :(得分:0)

我建议您创建另一个包含所有汽车列表的表,然后使用由部件组成的表,这样您就不会使用DISTINCT子句

试试这个:

SELECT DISTINCT c.CarMake
FROM Cars c
WHERE EXISTS(
   SELECT 'Wing'
   FROM Cars c2
   where c.carMake = c2.carMake
   AND c2.carPart = 'Wing'
)
AND EXISTS(
   SELECT 'Door'
   FROM Cars c2
   where c.carMake = c2.carMake
   AND c2.carPart = 'Door'
)
AND EXISTS(
   SELECT 'Windscreen'
   FROM Cars c2
   where c.carMake = c2.carMake
   AND c2.carPart = 'WindScreen'
)