sql - 数据等于数据中月份的结尾

时间:2016-09-21 15:32:25

标签: sql sql-server sql-server-2008 tsql date-range

我需要的数据等于同一个表中月份的结尾。

到目前为止我正在努力的是:<​​/ p>
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 ) )

我得到的错误是:

  

Msg 156,Level 15,State 1,Line 7关键字附近的语法不正确   '宣布'。消息102,级别15,状态1,行26错误的语法附近   ')'

提前感谢...

1 个答案:

答案 0 :(得分: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 )
相关问题