【问题标题】:Group by every year, year+9 and get total sum of count每年按年分组,年+9,得到计数的总和
【发布时间】:2021-04-13 04:07:12
【问题描述】:

如何按不同年份的特定范围分组(默认年份是不同的)?

输入:

my_table:

year  count
1961  2
1963  6
1969  3
1975  5
1976  9
1978  5
1983  3
1984  1
1985  3
1986  5
1987  6
1989  13
.
.
.

我试过了,

select sum(count) as total_count, 
       (year || '-' || year+9) as year_range 
from my_table 
group by year

但是,代码没有给出正确的结果。


预期输出:

total_count  year_range
11           1961-1970
 9           1963-1972
22           1969-1978
23           1975-1984
23           1978-1987
.
.
.

【问题讨论】:

  • 1961-1970 年的 9 是如何计算的?对我来说,这看起来像 11。
  • @GordonLinoff 我用过1961+9 = 1970

标签: sql sqlite group-by


【解决方案1】:

您可以通过自联接和聚合来做到这一点:

select sum(m2.count) total_count,  
       m1.year || '-' || (m1.year + 9) year_range
from my_table m1 left join my_table m2
on m2.year between m1.year and m1.year + 9
group by m1.year

请参阅demo
结果:

> total_count | year_range
> ----------: | :---------
>          11 | 1961-1970 
>           9 | 1963-1972 
>          22 | 1969-1978 
>          23 | 1975-1984 
>          21 | 1976-1985 
>          23 | 1978-1987 
>          31 | 1983-1992 
>          28 | 1984-1993 
>          27 | 1985-1994 
>          24 | 1986-1995 
>          19 | 1987-1996 
>          13 | 1989-1998 

【讨论】:

    【解决方案2】:

    你可以使用窗口函数;

    select t.*,
           sum(count) over (order by year range between current row and 9 following) as total_count
    from t;
    

    我不知道你是否需要year_range,但很简单:year || '-' || year + 9

    Here 是一个 dbfiddle。

    【讨论】:

    • @Pythoncoder 。 . .这确实需要更新版本的 SQLite。没有一点研究,我不确定究竟是哪个版本引入了这个功能(range 在支持窗口功能的原始版本中不起作用)。
    • 这个代码是给sqlite的吗?我仍然收到语法错误': near "(": syntax error
    • 我正在使用sqlite 3.22.0
    • @Pythoncoder 。 . .这在该版本中不起作用。您可能会考虑升级;那个版本已经有两年了。
    猜你喜欢
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多