【发布时间】:2015-02-27 20:53:30
【问题描述】:
我有如下两个维度表和一个事实表:
drop table if exists ref;
create table ref (country_id int not null, id_ref int not null);
insert into ref values(1,1);
insert into ref values(1,2);
drop table if exists conv;
create table conv (country_id int not null, id_ref int not null,id_conv int not null,item varchar(25));
insert into conv values (1,1,1,'AA');
insert into conv values (1,2,2,'CC');
insert into conv values(1,2,3,'CA');
insert into conv values(1,2,4,'CA');
drop table if exists fact;
create table fact as
select
r.country_id,c.item,
count(distinct r.id_ref) refs,
count(distinct c.id_conv) convs
from ref r
left join conv c
on r.country_id=c.country_id
and r.id_ref=c.id_ref
group by 1,2;
查询得到结果:
select f.country_id, sum(f.refs) refs,sum(f.convs) convs
from fact f
group by 1;
以上查询的结果是 1,3,4
但我期待 1,2,4
我怎样才能达到预期的效果或我的概念是错误的?
【问题讨论】:
-
你能解释一下为什么你期望 1,2,4 吗?您的事实表显然有 3 个参考结果,总和等于 3...为什么您需要按项目分组——这不起作用(它产生 1、2、4):sqlfiddle.com/#!2/22d3e8/3
-
因为 ref 表只有两行,所以如果我计算它们,我应该得到 2 作为 id_ref 的计数
标签: mysql sql group-by aggregation star-schema