我有以下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與熱量的蛋糕,但條件是現在(> 500),如果我將條件更改爲< 500,它只會返回超過500卡路里的蛋糕。這是怎麼回事?
嘗試將其移動到'having'子句 – McNets