2014-06-10 39 views
0

我想從查詢中獲取前6個月的數據。如何在SQL中只獲取特定月份的數據

即我必須只分組前六個月。

假設當前月份是六月話,我只希望一月份的數據&也是我不希望所有其他的前一個月比

誰能幫助我這個

SELECT 
    so_date 
FROM 
    RS_Sells_Invoice_Info_Master SIIM 
LEFT OUTER JOIN 
    RS_Sell_Order_Master AS SM ON SM.sell_order_no = SIIM.sell_order_no 
LEFT OUTER JOIN 
    RS_Sell_Order_Mapping AS SOM ON SOM.sell_order_no = SIIM.sell_order_no AND SIIM.product_id = SOM.product_id 
LEFT OUTER JOIN 
    RS_Inventory_Master AS IM ON IM.product_id = SIIM.product_id 
where 
    so_date between CAST(DATEADD(month, DATEDIFF(month, 0, so_date)-5, 0)AS DATE) and CAST(DATEADD(month, DATEDIFF(month, 0, so_date)-4, 0)AS DATE) 
+1

「過去六個月」比較是不一樣的「只希望一月份的數據」。你想要什麼 - 從1月份開始的所有數據,** 1月份(僅1月份)的所有數據**,或者可能有多個解釋的「前6個月」(當前日曆月和前5個月,前6個日曆月到當前日期,今天減去6個月到其他日期)。 – alroc

+1

重複,至少[這個問題](http://stackoverflow.com/questions/1424999/get-the-records-of-last-month-in-sql-server),雖然沒有任何現有的答案是理想的(現在添加更好的答案)。 –

回答

0

要獲取特定月份(6個月前)的所有數據,請使用以下where條款, 您需要比較月份和年份,以確保獲得正確的月份,即如果當前月份是月份,從去年開始。

where 
      datepart(Month, [so_date]) = datepart(Month, dateadd(month, -6,getdate())) 
     and 
      datepart(Year, [so_date]) = datepart(year, dateadd(month, -6,getdate())) 
+1

此解決方案無法使用索引,並且在大型表上會不必要地變慢。 – Tomalak

+0

對不起,我沒有你 –

1

假設電流月份是六月話,我只希望一月份的數據

這會工作

WHERE 
    so_date >= DATEADD(mm, -6, LEFT(CONVERT(VARCHAR, GETDATE(), 120), 8) + '01') 
    AND 
    so_date < DATEADD(mm, -5, LEFT(CONVERT(VARCHAR, GETDATE(), 120), 8) + '01') 

LEFT(CONVERT(VARCHAR, GETDATE(), 120), 8) + '01'爲您提供YYYY-MM-DD格式的當前月份的開始。其餘的都很簡單。

+0

nope dud這不起作用 –

+0

第一:我不認爲我們足夠接近你給我打電話「夥計」。第二:*「這是行不通的」*只是一個錯誤描述。 – Tomalak

+0

好的,先生,謝謝你的寶貴時間,我得到了解決方案 –

0

請檢查的例子,你用使用DateAdd功能減去6個月與之間功能

Declare @t table (name varchar(50), createddate datetime) 

Insert into @t values('ajay', GETDATE()-50),('ajay1', '2014-03-10'),('ajay2', '2013-12-09'),('ajay3', '2013-11-10') 
declare @currentdate datetime = getdate() , @sixmontholddate datetime = dateadd(MONTH, -6,getdate()) 

select @currentdate , @sixmontholddate 

select * from @t 

select * from @t where createddate between dateadd(MONTH, -6,getdate()) and GETDATE() 
+0

這是[SQL Server](http://sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/what-do-between-and-the-devil-have- in-common.aspx),讓我們不要。哎呀,你不應該試圖在任何服務器上使用連續範圍類型。 –

相關問題