从两个日期中进行选择,自动显示连续的行数据

时间:2019-03-30 05:37:04

标签: sql sql-server

我希望从两个日期中进行选择,自动显示连续的时间行数据。

例如:

Select * 
from somefunction('2013/5','2019/3');

预期结果:

Year | Month
-----+------
2013 |  5
2013 |  6
..   | ..
2013 | 12
..   | ..
..   | ..
2019 |  1
2019 |  2
2019 |  3

1 个答案:

答案 0 :(得分:2)

我已经解决了问题,并在此处提供了解决方案。

declare @dStart datetime = '2013/05/01'
,@dEnd datetime = '2019/03/31';

SELECT year(Dateadd(month,number,@dStart)) as year,month(Dateadd(month,number,@dStart)) as month
FROM master..spt_values
WHERE 
    type = 'P'
    AND number <= DATEDIFF(month, @dStart, @dEnd)
GO
year | month
---: | ----:
2013 |     5
2013 |     6
2013 |     7
2013 |     8
2013 |     9
2013 |    10
2013 |    11
2013 |    12
2014 |     1
2014 |     2
2014 |     3
2014 |     4
2014 |     5
2014 |     6
2014 |     7
2014 |     8
2014 |     9
2014 |    10
2014 |    11
2014 |    12
2015 |     1
2015 |     2
2015 |     3
2015 |     4
2015 |     5
2015 |     6
2015 |     7
2015 |     8
2015 |     9
2015 |    10
2015 |    11
2015 |    12
2016 |     1
2016 |     2
2016 |     3
2016 |     4
2016 |     5
2016 |     6
2016 |     7
2016 |     8
2016 |     9
2016 |    10
2016 |    11
2016 |    12
2017 |     1
2017 |     2
2017 |     3
2017 |     4
2017 |     5
2017 |     6
2017 |     7
2017 |     8
2017 |     9
2017 |    10
2017 |    11
2017 |    12
2018 |     1
2018 |     2
2018 |     3
2018 |     4
2018 |     5
2018 |     6
2018 |     7
2018 |     8
2018 |     9
2018 |    10
2018 |    11
2018 |    12
2019 |     1
2019 |     2
2019 |     3

db <>提琴here