列出2个日期之间的所有年,季度和季度日期

时间:2017-11-05 10:23:21

标签: sql-server date

我有两个日期(Date From = 2016-07-09和Date To = 2018-06-30)。我想列出以下所有年份和季度数字:

Code      No    From        To          Desc
AB-A       1    09-Jul-16   30-Jun-17   Year
AB-A       2    01-Jul-17   31-Jul-18   Year
AB-A       1    09-Jul-16   30-Sep-16   Qtr
AB-A       2    01-Oct-16   31-Dec-16   Qtr
AB-A       3    01-Jan-17   31-Mar-17   Qtr
AB-A       4    01-Apr-17   30-Jun-17   Qtr
AB-A       5    01-Jul-17   30-Sep-17   Qtr
AB-A       6    01-Oct-17   31-Dec-17   Qtr
AB-A       7    01-Jan-18   31-Mar-18   Qtr
AB-A       8    01-Apr-18   30-Jun-18   Qtr

我使用了以下内容,但结果不同。

DECLARE @start date='2016-07-09';
declare @end date = '2018-06-30';

SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS No,DateFrom, DateTo,'Qtr' AS Descr FROM (
select distinct year(dateadd(day,rnum,@start)) yr,@start AS DateFrom,@end AS DateTo,
datepart(quarter,dateadd(day,rnum,@start)) periodDesc
from (select row_number() over(order by (select null)) as rnum
      from master..spt_values) t
where dateadd(day,rnum,@start) <= @end) as myquery;

0 个答案:

没有答案