如何找到每三年发布的视频游戏数量?

How to find the number of video games released triannually?

假设我有一个 table videogames 并且我想找到发布的游戏数量 从 1997 年开始,每 3 年一次。

电子游戏

videogameid title year
1 GoldenEye 007 1997
2 Tomb Raider II 1997
3 Half-Life 1998
4 The Sims 2000
5 GTA (III) 2001
6 Kingdom Hearts 2003
7 World Of Warcraft 2004
8 ES4: Oblivion 2006
9 L.A. Noire 2011
10 Far Cry 3 2012
11 Diablo III 2012

从table开始,预期输出应该是Year (1997-1999) = 3, Year (2000-2002) = 2, 年份(2003 - 2005) = 2,年份(2006-2008) = 1,年份(2009 - 2011) = 1 和年份(2012-2014)= 2

这是我尝试解决的代码:

SELECT COUNT(videogameid) AS number_of_videogames
FROM videogames 
WHERE INTERVAL(1997,2,2,2,2,2,2)
GROUP BY YEAR;

出于某种原因,我得到了超过 100 ++ 行的答案,而每个间隔应该只有 6 行。

更新 2022-03-06

列出没有参考年份数字的总数似乎很奇怪 :-) 但如果这就是您想要的,请尝试:

WITH recursive ReleaseYears AS (
  -- build list of years 
  SELECT MIN(`year`) AS YearNum
  FROM   VideoGames
  UNION ALL
  SELECT YearNum + 1
  FROM   ReleaseYears
  WHERE  YearNum <= ( SELECT MAX(`year`) + 2 FROM VideoGames) 
)
SELECT COUNT(vg.videogameid) AS Num
FROM   ( -- group year numbers in groups of 3 
         SELECT FLOOR((ROW_NUMBER() OVER(ORDER BY (SELECT YearNum)) -1) / 3) + 1 AS YearGroup
               , YearNum
         FROM   ReleaseYears
       ) y LEFT JOIN VideoGames vg ON y.YearNum = vg.`year`
GROUP BY YearGroup       
HAVING COUNT(vg.videogameid) > 0

结果:

| Num |
| --: |
|   3 |
|   2 |
|   2 |
|   1 |
|   1 |

原答案

如果要以“(min-max)”格式显示年份:

WITH recursive ReleaseYears AS (
  SELECT MIN(`year`) AS YearNum
  FROM   VideoGames
  UNION ALL
  SELECT YearNum + 1
  FROM   ReleaseYears
  WHERE  YearNum <= ( SELECT MAX(`year`) + 2 FROM VideoGames) 
)
SELECT YearGroup
       , CONCAT_WS('-', MIN(YearNum), MAX(YearNum)) AS YearRange
       , COUNT(vg.videogameid) AS Num
FROM   (
         SELECT FLOOR((ROW_NUMBER() OVER(ORDER BY (SELECT YearNum)) -1) / 3) + 1 AS YearGroup
               , YearNum
         FROM   ReleaseYears
       ) y LEFT JOIN VideoGames vg ON y.YearNum = vg.`year`
GROUP BY YearGroup       
HAVING COUNT(vg.videogameid) > 0
;

结果:

YearGroup | YearRange | Num
--------: | :-------- | --:
        1 | 1997-1999 |   3
        2 | 2000-2002 |   2
        3 | 2003-2005 |   2
        4 | 2006-2008 |   1
        5 | 2009-2011 |   1
        6 | 2012-2014 |   2

db<>fiddle here

我认为你能得到的最简单的方法是使用递归 CTE 来生成你的年份,然后简单地 outer-join 将其添加到你的源数据中并像这样分成 3 个:

with recursive n as (
    select Min(year) yn, Ceiling((max(year)-Min(year))/3.0)*3 + min(year) maxyear, Min(year) minyear 
    from t
    union all
    select yn + 1, maxyear, minyear
    from n
    where yn < maxyear
)
select Min(yn) FromYear, Max(yn) toYear, Count(year) qty
from n
left join t on t.year=yn
group by floor((yn - minyear) /3);

Demo DB<>Fiddle