Sql 在配置单元查询中查找唯一项
我需要找到唯一国家种植的独特水果,它不应该由一个以上的国家种植。按唯一国家统计水果数量Sql 在配置单元查询中查找唯一项,sql,database,hive,Sql,Database,Hive,我需要找到唯一国家种植的独特水果,它不应该由一个以上的国家种植。按唯一国家统计水果数量 fruits | farming ------------------------------- apple | USA apple | INDIA apple | JAPAN apple | CHINA orange | USA orange | RUSSI
fruits | farming
-------------------------------
apple | USA
apple | INDIA
apple | JAPAN
apple | CHINA
orange | USA
orange | RUSSIA
orange | PAKISTAN
strawberry | INDIA
mango | AUSTRALIA
pineapple | AUSTRALIA
banana | INDIA
mosambi | INDIA
graphes | SRILANKA
graphes | NETHERLAND
输出:
INDIA | 3
AUSTRALIA | 2
草莓、香蕉、mosambi仅在印度种植,因此总共有3种独特的水果
芒果、菠萝仅在澳大利亚种植,因此总共有2种独特的水果一种方法使用两种聚合级别:
select country, count(*) as num_unique_fruits
from (select fruit, min(country) as country
from t
group by fruit
having count(*) = 1
) f
group by country;
请注意,如果只有一行,则mincountry是该行上的国家/地区
不存在更传统的方法:
第一种可能在Hive中性能更好,但如果考虑性能的话,两种方法都值得尝试。太棒了,你节省了我的时间。多谢各位
select country, count(*)
from t
where not exists (select 1 from t t2 where t2.fruit = t.fruit and t2.country <> t.country)
group by country;