【问题标题】:star schema aggregation issue星型模式聚合问题
【发布时间】: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


【解决方案1】:

我认为你有一个错误:

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=r.country_id
and r.id_ref=c.id_ref
group by 1,2;

请尝试

left join conv c
    on r.country_id=c.country_id
    and r.id_ref=c.id_ref

而不是

left join conv c
    on r.country_id=r.country_id
    and r.id_ref=c.id_ref

(以下部分看起来像错误r.country_id=r.country_id - 始终为真表达式)

【讨论】:

    【解决方案2】:

    您的异常与此查询有关。 您要加入两个基于国家/地区的表格。他们将是 4 个匹配的记录。在按国家 & 项目分组后,将有三个记录。总结与项目不同的 refid。实际结果是正确的。

    country_id 项目参考转化 1 AA 1 1 1 CA 1 2 1 抄送 1 1

    对于您的期望,查询将是

    select 
    r.country_id,
    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  r.country_id

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多