我有一张跨越数年的事件表。
title start_year end_year
Event 1 1976 1983
Event 2 1977 2002
Event 3 2018 2019
Event 4 2003 2019
期望的结果:
我想输出过去 50 年来每年“运行”事件的总数。 (1976年,只有一项赛事在进行。1977年,同一赛事仍在进行,另外还举办了另一项赛事。)
year total_events
1976 1
1977 2
1976 2
示例查询:
此查询返回一年的总计。让它输出过去 50 年的结果的最佳方法是什么?
SELECT COUNT(*) AS total_events
FROM `events`
WHERE start_year <= 1976
AND end_year >= 1976
最佳答案
基本上,您需要一个年份列表。如果您手边没有,您可以在派生表中创建一个列表:
select y.year,
(select count(*)
from t
where y.year between t.start_year and t.end_year
) as num_events
from (select 1976 as year union all
select 1977 as year union all
select 1978 as year union all
. . .
) y;
关于mysql - 计算每年的运行事件总数以及跨多年的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56800383/