0

我正在尝试提出一个排除某些具有特定值的记录的查询。这是我的代码片段:

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'
4

3 回答 3

2

代码如下,但您提供的表格需要规范化并将其拆分为多个表格。

 select [Id],[dish],[dishtype]  
 from #myMenu  
 group by [Id],[dish],[dishtype]
 having sum(Case When ingredient='nuts' Then 1 Else 0 End)=0
于 2013-09-16T03:08:08.407 回答
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
于 2013-09-16T02:02:41.213 回答
0
Select *
FROM myMenu
WHERE ingredient != 'nuts' AND
dish NOT LIKE '%macadamia%' AND
dish NOT LIKE '%cashew%'

如果您只想包括主菜,您可以添加 AND discType = 'main'

于 2013-09-16T01:57:48.367 回答