Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 每年分组,每年+;9并得到计数的总和_Sql_Sqlite_Group By - Fatal编程技术网

Sql 每年分组,每年+;9并得到计数的总和

Sql 每年分组,每年+;9并得到计数的总和,sql,sqlite,group-by,Sql,Sqlite,Group By,如何为每个不同的年份按特定范围分组(默认情况下,年份是不同的) 输入: 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 . . . total_count year_range 11 1961-1970 9 1963-1972 22 1969

如何为每个不同的年份按特定范围分组(默认情况下,年份是不同的)

输入:

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
.
.
.
total_count  year_range
11           1961-1970
 9           1963-1972
22           1969-1978
23           1975-1984
23           1978-1987
.
.
.
我试过了

select sum(count) as total_count, 
       (year || '-' || year+9) as year_range 
from my_table 
group by year
但是,代码没有给出正确的结果


预期输出:

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
.
.
.
total_count  year_range
11           1961-1970
 9           1963-1972
22           1969-1978
23           1975-1984
23           1978-1987
.
.
.

你可以使用窗口功能

select t.*,
       sum(count) over (order by year range between current row and 9 following) as total_count
from t;
我不知道您是否需要
year\u范围
,但那很简单:
year | |'-“| | year+9


是一个dbfiddle。

您可以通过自连接和聚合来实现:

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
请参阅。
结果:


如何计算1961-1970年的9?对我来说这看起来像11。@GordonLinoff我用了
1961+9=1970
@Pythoncoder。这确实需要更新版本的SQLite。没有一点研究,我不确定到底是哪个版本引入了此功能(
range
在支持窗口功能的原始版本中不起作用)。此代码是用于
sqlite
?我仍在获取语法错误<代码>:“接近”(语法错误 >我使用的是代码> SQLite 3.22.0 @ PythOn编码器……在那个版本中不起作用。您可能会考虑升级;那个版本已经两年了。