2014-05-01 170 views
0

我正在嘗試在sql server中按月份YTD。我在2月份沒有任何記錄。如何在sql server 2008中按月份獲取月份名稱?

select WO,CreatedDate,Item ,(DATENAME(Month,CreatedDate)) as [Month], 
    DATEPART(yyyy ,CreatedDate) as [Year]from #temptbale 
Group by WO,CreatedDate,Item 
Order by Month 

輸出:

WO  Date   Item  Month 
WO-1009 2014-04-29 Bicycle - Blue April 
WO-1010 2014-04-29 Bicycle - Blue April 
WO-1012 2014-01-20 Bicycle - Blue January 
WO-1013 2014-01-24 Bicycle - Blue January 
WO-1021 2014-03-12 Bicycle - Red March 
WO-1022 2014-03-12 Bicycle - Red March 

慾望結果:

WO  Date   Item  Month 
WO-1009 2014-04-29 Bicycle - Blue April 
WO-1010 2014-04-29 Bicycle - Blue April 
WO-1012 2014-01-20 Bicycle - Blue January 
WO-1013 2014-01-24 Bicycle - Blue January 
WO-1021 2014-03-12 Bicycle - Red March 
WO-1022 2014-03-12 Bicycle - Red March 
NULL   NULL  NULL   February 
+0

試由Concat組成(月(CreatedDate),年(CreatedDate))或類似概念的東西。 –

回答

1

您可以使用一個表變量與月的名稱並加入您的查詢到該變量

DECLARE @Months TABLE (Month_Value INT, Month_Name NVARCHAR(20)) 
INSERT @Months VALUES (1, 'January'),(2, 'February'),(3, 'March'),(4, 'April'),(5, 'May'),(6, 'June'), 
    (7, 'July'),(8, 'August'),(9, 'September'),(10, 'October'),(11, 'November'),(12, 'December') 

;with CTE AS (
    select WO,CreatedDate,Item ,DATENAME(Month,CreatedDate) as [Month], 
     DATEPART(yyyy ,CreatedDate) as [Year] from #temptbale 
    Group by WO,CreatedDate,Item) 

select CTE.WO, CTE.CreatedDate, CTE.Item, coalesce(CTE.[Month], M.Month_Name), CTE.[Year] from CTE 
full outer join @Months M ON CTE.[Month] = M.Month_Name 
where Month_Value <= DATEPART(month, getdate()) 
order by coalesce(CTE.[Month], M.Month_Name) 
+0

我只得到YTD.Current Year到本月。但使用上面的查詢我有12個月的名字。 – Kavitha

+0

@Kavitha你從哪裏獲得當月?今天的日期? – Szymon

+0

是的,僅使用今日日期... – Kavitha