2017-06-13 35 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(年,月,日)... –

相關問題