hive SQL查询,以查找城市方面的男性和女性计数

gywdnpxw  于 2022-11-05  发布在  Hive
关注(0)|答案(3)|浏览(164)

假设我们有下面的表:

city    gender
 abc    m
 abc    f
 def    m

所需输出:

city    f_count   m_count
 abc    1          1
 def    0          1

请帮助我用配置单元、MySQL或SQL Server语法编写查询。我需要配置单元语法。
感谢您发送编修。

elcex8rz

elcex8rz1#

请尝试:

select city,sum(gender='f') as f_count,sum(gender='m') as m_count
from my_table
group by city;

结果:

city  f_count m_count
abc         1      1
def         0      1

Demo

gwo2fgha

gwo2fgha2#

数据库服务器:

select 
 city
,count(case when gender = 'm' then 1 else null end) as m_count
,count(case when gender <> 'm' then 1 else null end) as f_count
from table_name 
group by city

结果:

city  | f_count   | m_count
abc   |      1    |    1
def   |      0    |    1
cbjzeqam

cbjzeqam3#

select city, sum(male),sum(female) from
(select city ,count(gender) as male,0 as female from temp where gender='M' group by city 
union 
select city , 0,count(gender) as female from temp where gender='F'group by city)
group by city;

相关问题