我有以下结构:
具有typ1和typ2的多个事件的日,其中typ1和typ2具有各自日期的外键。 Typ2也有持续时间。
现在我想计算所有typ1事件,所有typ2事件和typ2持续时间的总和。
示例数据:
天:
ID = 1 | Date = yesterday | ...
TYP1:
ID = 1 | FK_DAY = 1 | ...
ID = 2 | FK_DAY = 1 | ...
TYP2:
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;
答案 0 :(得分: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
答案 1 :(得分: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;