根据给出的参数,我有办法获得月份的年份吗?
DECLARE @StartDate DATETIME,
@EndDate DATETIME;
SELECT
@StartDate = '2016-02-01',
@EndDate = '2017-03-01';
SELECT
/*is there a way for me to get the year of months based on the parameter dates*/
/*DATEPART(YEAR, DATEADD(YEAR, x.number, @StartDate)) AS Year,*/
DATEPART(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS Month,
DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS MonthName
FROM
master.dbo.spt_values x
WHERE
x.type = 'P'
AND x.number <= DATEDIFF(MONTH, @StartDate, @EndDate)
我的查询结果......
我想要的是,从2月到12月它将有2016年的一年,从1月到3月它将有2017年......基于我参考的参数。给了..
提前致谢。
答案 0 :(得分:3)
试试这个:
SELECT YEAR(y.dt) AS Year,
MONTH(y.dt) AS Month,
DATENAME(MONTH, y.dt) AS MonthName
FROM master.dbo.spt_values x
CROSS APPLY (SELECT DATEADD(MONTH, x.number, @StartDate)) AS y(dt)
WHERE x.type = 'P'
AND x.number <= DATEDIFF(MONTH, @StartDate, @EndDate)