我有两张桌子:
Ingredients
包含以下字段:
ID
(数字)Ingredient
(文字)Plural
(文字)
其中Ingredient
是成分的名称,Plural
是其复数名称(例如:橄榄,橄榄)
和另一个表Shopping_Ingredients
,其中包含字段:
Amount
(数字),Ingredient_ID
(数字)
我需要一个SQL语句,为所有表Amount
和Shopping_Ingredients
名称返回Ingredient
的附加值(如果它没有复数或复数,则为奇数) )
示例:
Ingredients
:
1'苹果''苹果'
2'大蒜'''
Shopping_Ingredients
:
1 1
2 1
3 1
2 2
3 2
返回:
6'苹果'
5'大蒜'
答案 0 :(得分:2)
由于您没有指定您使用的数据库引擎,这里是适用于SQL Server 2000及更新版本的查询版本(也可能适用于MySQL):
SELECT
T.Amount,
CASE
WHEN T.Amount <= 1 THEN I.Ingredient
ELSE
CASE WHEN ISNULL(I.Plural, '') = '' THEN I.Ingredient ELSE I.Plural END
END
FROM
(
SELECT SUM(Amount) Amount, Ingredient_ID FROM Shopping_Ingredients GROUP BY Ingredient_ID
) AS T
INNER JOIN Ingredient I ON
I.Ingredient_ID = T.Ingredient_ID
这里适用于SQL Server 2005及更新版本:
;WITH CTE
AS
(
SELECT SUM(Amount) Amount, Ingredient_ID FROM Shopping_Ingredients GROUP BY Ingredient_ID
)
SELECT
T.Amount,
CASE
WHEN T.Amount <= 1 THEN I.Ingredient
ELSE
CASE WHEN ISNULL(I.Plural, '') = '' THEN I.Ingredient ELSE I.Plural END
END
FROM CTE AS T
INNER JOIN Ingredient I ON
I.Ingredient_ID = T.Ingredient_ID
答案 1 :(得分:0)
只需键入,但应该让你非常接近
select count(*),
case x.plural='' then x.ingredient else x.plural end as Ingredient
from ingredients x
join Shopping_Ingredients y on y.ingredient_id=x.id
group by x.ingredient,x.plural
答案 2 :(得分:0)
尝试:
select sum(s.Amount),
case sum(s.Amount)
when 1 then max(i.Ingredient)
else coalesce(max(i.Plural), max(i.Ingredient))
end
from Ingredient i
left join Shopping_Ingredients s on s.Ingredient_ID = i.ID
group by i.ID
答案 3 :(得分:0)
select a.amount, CASE WHEN a.plural is null then a.ingredient else plural end
(select i.id as id, i.ingredient as ingridient, i.plural as plural, SUM(si.amount) as amount
from ingredients i, shopping_ingridents si
where si.ingredient_id = i.id
group by i.id, i.ingredient, i.plural) a
想法是先用SUM选择所有数据,即选择ingridient,复数和Sum of amount,然后检查复数是否存在选择复数,否则选择ingridient。