2016-09-21 36 views
-1

我需要等於同一個表中月份結束的數據。sql - 數據等於數據中的月份結尾

什麼到目前爲止,我掙扎是:

SELECT * FROM LG_006_01_EMFLINE H 

where h.DATE_ in (


declare @start datetime 
declare @end datetime 

select @Start = (select MIN(mm.date_) as minimum FROM LG_006_01_EMFLINE mm where mm.accountcode like '335%' and mm.DATE_ > '2016-04-01') 
select @End = (select MAX(nn.date_) FROM LG_006_01_EMFLINE nn where nn.accountcode like '335%' and nn.DATE_ > '2016-04-01') 
;With CTE as 
(
Select @Start as Date,Case When DatePart(mm,@Start)<>DatePart(mm,@Start+1) then 1 else 0 end as [Last] 
UNION ALL 
Select Date+1,Case When DatePart(mm,Date+1)<>DatePart(mm,Date+2) then 1 else 0 end from CTE 
Where Date<@End 
) 

Select date from CTE 
where [Last]=1 OPTION (MAXRECURSION 0)) 

我得到的錯誤是:

消息156,級別15,狀態1,第7行關鍵字 附近的語法不正確「聲明」。 Msg 102,Level 15,State 1,Line 26在 ')'附近的語法錯誤。

在此先感謝...

+0

什麼味道的SQL? MySQL,SQL Server等?另外,爲什麼你的'declare'語句在select中? – JohnHC

+1

你不能在子選擇內部有一個'declare'。 ';'在**聲明的結尾**。不在子選擇 –

+0

@JohnHC SQL Server 2008 –

回答

0

你說你in語句中的代碼工作對自己很好,但作爲a_horse_with_no_name正確地指出,你不能有內declare陳述或cte小號子選擇。

因此,您需要稍微重新排列您的查詢。由於您還沒有提供源模式或數據,我還沒有能夠測試這個:

declare @start datetime 
declare @end datetime 

select @Start = (select MIN(mm.date_) as minimum 
       FROM LG_006_01_EMFLINE mm 
       where mm.accountcode like '335%' 
        and mm.DATE_ > '20160401' -- Remove the hyphens to ensure SQL knows exactly what your date is, avoiding localisation issues. 
       ) 

select @End = (select MAX(nn.date_) 
       from LG_006_01_EMFLINE nn 
       where nn.accountcode like '335%' 
        and nn.DATE_ > '20160401' -- Remove the hyphens to ensure SQL knows exactly what your date is, avoiding localisation issues. 
       ) 

;With CTE as 
(
Select @Start as Date 
     ,Case When DatePart(mm,@Start) <> DatePart(mm,@Start+1) then 1 else 0 end as [Last] 

union all 

Select Date+1 
     ,Case When DatePart(mm,Date+1) <> DatePart(mm,Date+2) then 1 else 0 end 
from CTE 
Where Date < @End 
) 
select * 
from LG_006_01_EMFLINE H 
where h.DATE_ in (
       Select date 
       from CTE 
       where [Last]=1 
       ) 
option (maxrecursion 0) 
+0

非常感謝,作品像一個魅力! 我根本不知道如何重新安排代碼! –

相關問題