【发布时间】:2018-11-13 07:36:52
【问题描述】:
我有一张这样的桌子。我想选择基于group_id 而不是Vegetables 和Nuts 组合在一起的Fruits。对于Vegetable 和Nuts,我都想要。
group_id name type
-----------------------------------
1 Green Apple Fruit
1 Red Apple Fruit
1 Blue Apple Fruit
2 Green Peas Vegetable
2 Snow Peas Vegetable
2 Another Pea Vegetable
3 Ground Nut Nuts
3 Peanut Nuts
4 Carrot Vegetable
这就是我现在尝试的方式。这很好用,但我想知道是否有更简单的方法。
select * from Grocessaries GROUP BY group_id HAVING type in ('Fruit', 'Drinks')
UNION all
select * from Grocessaries where type in ('Vegetable', 'Nuts')
基本上,我想要这样的结果(分组的水果和所有蔬菜和坚果)
group_id name type
-----------------------------------
1 Green Apple Fruit
2 Green Peas Vegetable
2 Snow Peas Vegetable
2 Another Pea Vegetable
3 Ground Nut Nuts
3 Peanut Nuts
4 Carrot Vegetable
【问题讨论】:
-
你能详细说明一下逻辑吗?为什么蓝苹果和红苹果被过滤掉了,而雪豆却留在了你想要的输出中?
-
在第一个查询中
GROUP BY group_id毫无意义,因为您没有使用任何聚合函数.. -
您似乎在混合分组和排序
-
订单对我来说不是问题。我已经从查询中删除了订购部分。我只关心分组部分。
-
为什么是
Green Apple Fruit而不是Red Apple Fruit或Blue Apple Fruit?