6

我有以下结构:

Day 有 typ1 和 typ2 的多个事件,其中 typ1 和 typ2 具有各自日期的外键。Typ2 也有持续时间。

现在我想计算所有 typ1 事件、所有 typ2 事件和 typ2 持续时间的总和。

示例数据:

天:

ID = 1 | Date = yesterday | ...

类型 1:

ID = 1 | FK_DAY = 1 | ...

ID = 2 | FK_DAY = 1 | ...

类型 2:

ID = 1 | FK_DAY = 1 | duration = 10

ID = 2 | FK_DAY = 1 | duration = 20

我现在想要结果:

Day.ID = 1 | countTyp1 = 2 | countTyp2 = 2 | sumDurationTyp2 = 30

我的问题是总和,我需要类似“不同 typ2.ID 的总和”之类的东西......有谁知道解决这个问题的方法?

我正在使用类似以下的东西,但这当然不能按我想要的方式工作:

SELECT day.id,
   count( DISTINCT typ1.id ),
   count( DISTINCT typ2.id ),
   sum( duration ) AS duration
FROM days
   LEFT JOIN typ
          ON day.id = typ1.id
   LEFT JOIN typ2
          ON day.id = typ2.id
GROUP BY day.id;
4

2 回答 2

14

我对此的一般方法是在加入之前预先聚合每个表。

部分原因是您实际上并没有对不同的值求和(如果两行中的每一行都有10,答案仍然是20)。

但主要是因为它实际上更简单。子查询进行聚合,然后连接都是 1:1。

SELECT
  days.id,
  typ_agg.rows,
  type2_agg.rows,
  type2_agg.duration
FROM
  days
LEFT JOIN
  (SELECT fk_day, COUNT(*) as rows FROM typ GROUP BY fk_day)  AS typ_agg
    ON days.id = typ_agg.fk_day
LEFT JOIN
  (SELECT fk_day, COUNT(*) as rows, SUM(duration) as duration FROM typ2 GROUP BY fk_day)  AS typ2_agg
    ON days.id = typ2_agg.fk_day
于 2012-10-16T13:03:41.250 回答
0
SELECT day.id,
   count( DISTINCT typ1.id ),
   count( DISTINCT typ2.id ),
   (select sum( t2.duration )
    from typ2 t2
    where t2.id = day.id
   ) AS duration
FROM days
   LEFT JOIN typ
          ON day.id = typ1.id
   LEFT JOIN typ2
          ON day.id = typ2.id
GROUP BY day.id;
于 2012-10-16T12:55:01.293 回答