我有以下sql图:
Category:
id_category
category_name
Measurement
id_measurement
name_measurement
Ingredient
id_ingredient
name_ingredient
category_id
measurement_id
nrOfCal
IngredientCake
id_ingredient
cake_code
quantities
Cake
cake_code
cake_name
我不知道如何显示所有代码和名称少于500卡路里的蛋糕。 我尝试了什么:
select [Cake].cake_code , [Cake].cake_name
from [Cake]
inner join [Ingredient_Cake]
on ([Cake].cake_code = [Ingredient_Cake].cake_code)
inner join [Ingredient]
on ([Ingredient_Cake].id_ingredient = [Ingredient].id_ingredient)
where sum([Ingredient].nrOfCal) < 500
group by [Cake].cake_code;
但无论如何它给了我错误:
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
任何解决方案?
编辑:
select [Cake].cake_code,
[Cake].cake_name
from [Cake]
inner join [Ingredient_Cake]
on ([Cake].cake_code = [Ingredient_Cake].cake_code)
inner join [Ingredient]
on ([Ingredient_Cake].id_ingredient = [Ingredient].id_ingredient)
group by [Cake].cake_code, [Cake].cake_name
having sum(nrOfCal*quantities) > 500;
我已经编辑了,现在有趣的部分是,如果我这样做,它会返回我应该如何,卡路里低于500的蛋糕,但现在条件是(&gt; 500),如果我改变条件为&lt; 500,它只给我带来超过500卡路里的蛋糕。发生了什么事?
答案 0 :(得分:0)
尝试将聚合移动到having子句:
select [Cake].cake_code,
[Cake].cake_name
from [Cake]
inner join [Ingredient_Cake]
on ([Cake].cake_code = [Ingredient_Cake].cake_code)
inner join [Ingredient]
on ([Ingredient_Cake].id_ingredient = [Ingredient].id_ingredient)
group by [Cake].cake_code, [Cake].cake_name
having sum([Ingredient].nrOfCal) < 500;
答案 1 :(得分:0)
由于您的条件是汇总值,因此您需要使用HAVING
子句(在group by
之后执行)而不是where
:
select [Cake].cake_code , [Cake].cake_name from [Cake]
inner join [Ingredient_Cake] on ([Cake].cake_code =
[Ingredient_Cake].cake_code)
inner join [Ingredient] on ([Ingredient_Cake].id_ingredient
= [Ingredient].id_ingredient)
group by [Cake].cake_code
Having sum([Ingredient].nrOfCal) < 500