我正在尝试提出一个排除某些具有特定值的记录的查询。 这是我的代码片段:
CREATE TABLE #myMenu
([Id] int, [dish] varchar(100), [dishtype] varchar(10), [amount] int, [ingredient] varchar(10))
;
INSERT INTO #myMenu
([Id], [dish], [dishtype], [amount], [ingredient])
VALUES
(1, 'salad', 'appetizer', 1, 'nuts'),
(1, 'salad', 'appetizer', 1, 'lettuce'),
(2, 'chicken cashew nuts', 'main', 2, 'chicken'),
(2, 'chicken cashew nuts', 'main', 9, 'nuts'),
(3, 'chicken marsala', 'main', 0, 'chicken'),
(3, 'chicken marsala', 'main', 0, 'pepper'),
(4, 'roast pork macadamia', 'main', 2, 'nuts'),
(4, 'roast pork macadamia', 'main', 2, 'pork')
;
现在我要做的是选择所有没有坚果的菜肴。哪个应该只有:
(3, 'chicken marsala', 'main'
答案 0 :(得分:2)
代码如下,但您提供的表需要进行规范化并将其拆分为多个表。
select [Id],[dish],[dishtype]
from #myMenu
group by [Id],[dish],[dishtype]
having sum(Case When ingredient='nuts' Then 1 Else 0 End)=0
答案 1 :(得分:1)
select M.Id, M.Dish, M.DishType
from #myMenu as M inner join
( select Id, Sum( case when Ingredient = 'nuts' then 1 end ) as Nutty from #MyMenu group by Id ) as Nuts
on Nuts.Id = M.Id and Nuts.Nutty is NULL
group by M.Id, M.dish, M.dishtype
或:
select distinct M.Id, M.Dish, M.DishType
from #myMenu as M inner join
( select Id, Sum( case when Ingredient = 'nuts' then 1 end ) as Nutty from #MyMenu group by Id ) as Nuts
on Nuts.Id = M.Id and Nuts.Nutty is NULL
答案 2 :(得分:0)
Select *
FROM myMenu
WHERE ingredient != 'nuts' AND
dish NOT LIKE '%macadamia%' AND
dish NOT LIKE '%cashew%'
如果您只想包含主菜,可以添加AND dishType ='main'