如何正确加入以在同一列上进行两次聚合?

时间:2015-07-21 00:03:43

标签: sql join

表的颗粒类似于state_id | county_id | city_id | eventtype。 eventtype是二进制的;它等于1或2。 我希望按所有3列进行分组,并查看事件类型的总和,它等于1和2.如何正确执行此操作?

当我进行

的内连接时
select *
from 
(state_id, county_id, city_id, sum(eventtype) as views
select 
poptable
where eventtype = 1 
group by state_id, county_id, city_id) l
INNER JOIN
(state_id, county_id, city_id, sum(eventtype) as passes
select 
poptable
where eventtype = 2
group by state_id, county_id, city_id) r
ON l.state_id = r.state_id
and l.county_id = r.county_id
and l.city_id = r.city_id

我得到大约500行。但如果我做一个完整的外连接,我会得到大约3000行。我知道会有缺少的组合,所以如何让它们一起出现呢?

2 个答案:

答案 0 :(得分:1)

select state_id, country_id, city_id, 
case when eventtype = 1 then sum(eventtype) end as passes,
case when eventtype = 2 then sum(eventtype) end as views
from tablename where eventtype in (1,2)
group by state_id, country_id, city_id

这是你想要做的吗?

答案 1 :(得分:1)

我认为你只想要条件聚合:

select state_id, county_id, city_id,
       sum(case when eventtype = 1 then 1 else 0 end) as views_1,
       sum(case when eventtype = 2 then 1 else 0 end) as views_2
from poptable
group by state_id, county_id, city_id;

我不确定你为什么这么做sum(eventtype)。你想要" 1"这似乎很奇怪在第一种情况下总结和" 2"在第二个。