2015-07-21 61 views
0

表中的谷物类似于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

你正在使用什么数据库? –

回答

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”。

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 

难道这就是你想干什么?

相关问题