我简化了一个表作为示例
tray| food
-------+-------
1 | fruit
2 | veg
2 | fruit
2 | meat
3 | meat
4 | bread
我想要找到的每种水果,是仅包含该类型食物的托盘数量。所以输出应该如下所示:
food| count
-------+-------
fruit | 1
veg | 0
meat | 1
bread | 1
我尝试写一个查询:
SELECT fruit, COUNT(*)
FROM Inventory
WHERE NOT EXISTS (SELECT *
FROM Inventory I
WHERE I.tray = tray AND I.fruit<>fruit)
GROUP BY fruit;
但是返回的表格不正确,看起来我的子查询错了,但这对我来说是合乎逻辑的。
food | count
-------+-------
fruit | 2
veg | 1
bread | 1
meat | 2
看起来托盘2对于水果,肉类和蔬菜只计数一次,但不应该。但不应该被我的NOT EXISTS子查询排除吗?我该如何解决这个问题?
答案 0 :(得分:0)
聪明的小问题。这是一个解决方案:
select f.food, count(t.tray)
from (select distinct food from t
) f left join
(select t.tray, min(food) as minfood, max(food) as maxfood
from tray t
group by tray
) t
on f.food = t.minfood and f.food = t.maxfood
group by f.food;
计算为零表示查询left join
和group by
有用。
答案 1 :(得分:0)
select i1.food,
count(ft.tray)
from inventory i1
left join (
select i1.tray,
count(distinct i1.food) as num_food
from inventory i1
group by i1.tray
) ft on i1.tray = ft.tray and num_food = 1
group by i1.food;
内部查询(ft
)计算每个托盘不同食物的数量。外部(主要)查询计算仅包含单一类型食物的托盘的每种食物的托盘数量。