【发布时间】:2020-10-22 08:41:22
【问题描述】:
我在 Oracle 中有下表
Fruit | Color
-------+-------
Apple | Red
Apple | Green
Cherry | Red
我需要下面的总结,只有颜色不同的那些
Fruit | Colors
------+-------
Apple | 2
【问题讨论】:
标签: sql oracle select group-by count
我在 Oracle 中有下表
Fruit | Color
-------+-------
Apple | Red
Apple | Green
Cherry | Red
我需要下面的总结,只有颜色不同的那些
Fruit | Colors
------+-------
Apple | 2
【问题讨论】:
标签: sql oracle select group-by count
只需使用聚合,在having 子句中使用过滤器:
select fruit, count(*) colors
from mytable
group by fruit
having count(*) > 1
这假定(fruit, color) 上没有重复项,如您的示例数据所示。否则,您需要count(distinct color) 而不是count(*):
select fruit, count(distinct color) colors
from mytable
group by fruit
having count(distinct color) > 1
【讨论】:
这是一个group by,用于过滤聚合结果:
select fruit, count(distinct color) as colors
from the_table
group by fruit
having count(distinct color) > 1;
count(distinct color) 中的 distinct 使它只计算每种水果的不同颜色。
【讨论】: