【问题标题】:Count total running events per year with events that range over multiple years计算每年的总运行事件以及跨越多年的事件
【发布时间】:2019-11-10 00:39:21
【问题描述】:

我有一张跨越几年的事件表。

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

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    基本上,您需要一份年份列表。如果手头没有,可以在派生表中创建一个列表:

    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;
    

    【讨论】:

    • 非常感谢!我正在考虑做这样的事情,但感觉像是不好的做法,对吧?特别是如果我将其扩展到 100 年左右?
    • 不,这很好而且很快。也可以使用几天:stackoverflow.com/questions/2157282/…。对读者来说有点难:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多