2017-07-02 79 views
0

我有以下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卡路里的蛋糕。這是怎麼回事?

+0

嘗試將其移動到'having'子句 – McNets

回答

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; 
+0

現在錯誤消失了,但sql不起作用.. – IleNea

+0

我不知道您的數據,也許您應該用nrOfCal乘以IngredientCake.quantities? – McNets

+0

我編輯過,現在很奇怪。 – IleNea

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