2017-06-13 37 views

回答

1

几个月的某一年的即席表:

declare @year date = dateadd(year,datediff(year,0,getdate()),0) 
;with Months as (
    select 
     MonthStart=dateadd(month,n,@year) 
    from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11)) t(n) 
) 
select MonthStart 
from Months 

rextester演示:http://rextester.com/POKPM51023

回报:

+------------+ 
| MonthStart | 
+------------+ 
| 2017-01-01 | 
| 2017-02-01 | 
| 2017-03-01 | 
| 2017-04-01 | 
| 2017-05-01 | 
| 2017-06-01 | 
| 2017-07-01 | 
| 2017-08-01 | 
| 2017-09-01 | 
| 2017-10-01 | 
| 2017-11-01 | 
| 2017-12-01 | 
+------------+ 

第一部分:dateadd(year,datediff(year,0,getdate()),0)增加了,因为年数1900-01-01至日期1900-01-01。所以它会返回一年中的第一个日期。您还可以将year替换为其他级别的截断:年,季,月,日,小时,分钟,秒等等。

第二部分使用common table expressiontable value constructor (values (...),(...))来源数字0-11,这是作为月份添加到年初。

0

不知道为什么你需要递归...但对于一个月的第一天,你可以尝试查询象下面这样:

Select Dateadd(day,1,eomonth(Dateadd(month, -1,getdate()))) 
0
declare @year date = dateadd(year,datediff(year,0,getdate()),0) 
;WITH months(MonthNumber) AS 
(
SELECT 0 
UNION ALL 
SELECT MonthNumber+1 
FROM months 
WHERE MonthNumber < 11 
) 
select dateadd(month,MonthNumber,@year) 
from months 
2

如果2012+,你可以使用DateFromParts()

至获取日期的列表

Select D = DateFromParts(Year(GetDate()),N,1) 
From (values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) N(N) 

返回

D 
2017-01-01 
2017-02-01 
2017-03-01 
2017-04-01 
2017-05-01 
2017-06-01 
2017-07-01 
2017-08-01 
2017-09-01 
2017-10-01 
2017-11-01 
2017-12-01 

编辑跨数

要获得交易(按月假设)。它成为一个左的小事加入到创建日期

-- This is Just a Sample Table Variable for Demonstration. 
-- Remove this and Use your actual Transaction Table 
-------------------------------------------------------------- 
Declare @Transactions table (TransDate date,MoreFields int) 
Insert Into @Transactions values 
('2017-02-18',6) 
,('2017-02-19',9) 
,('2017-03-05',5) 


Select TransMonth = A.MthBeg 
     ,TransCount = count(B.TransDate) 
From (
     Select MthBeg = DateFromParts(Year(GetDate()),N,1) 
       ,MthEnd = EOMonth(DateFromParts(Year(GetDate()),N,1)) 
     From (values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) N(N) 
    ) A 
Left Join @Transactions B on TransDate between MthBeg and MthEnd 
Group By A.MthBeg 

返回

TransMonth TransCount 
2017-01-01 0 
2017-02-01 2 
2017-03-01 1 
2017-04-01 0 
2017-05-01 0 
2017-06-01 0 
2017-07-01 0 
2017-08-01 0 
2017-09-01 0 
2017-10-01 0 
2017-11-01 0 
2017-12-01 0 
+0

的感谢!我真的很感谢这个简单的解决方案 –

+0

谢谢!你能提供一个你的想法的小解释吗? – Proffesore

+0

@Poffesore FROM部分生成12个记录(1-12),字段名称为N.然后我们简单地使用N作为DateFromParts()中的月份。 ... DateFromPart(年,月,日)... –

相关问题