基于当前月份的动态SQL查询

时间:2018-03-02 10:10:17

标签: sql dynamicquery

下面是一个SQL代码,它根据月度数据摘要的并集创建一个表:

-- Oct 2017

select distinct  a.device_id ,201710 as month_id,
case when group_descr in ('BASE') then 'Basic'
     when group_descr in ('VALUES') then 'Valuable'
     when group_descr in ('PREFERRENCE') then 'Preferr'
     else 'Other'
end as Class
from dbo.DEVICE_HIST a
where a.expired >= '2017-10-01' and a.EFFTV <'2017-10-31'

union

-- Nov 2017
select distinct  a.device_id ,201711 as month_id,
case when group_descr in ('BASE') then 'Basic'
     when group_descr in ('VALUES') then 'Valuable'
     when group_descr in ('PREFERRENCE') then 'Preferr'
     else 'Other'
end as Class
from dbo.DEVICE_HIST a
where a.expired >= '2017-11-01' and a.EFFTV <'2017-11-30'

union

-- Dec 2017
select distinct  a.device_id ,201712 as month_id,
case when group_descr in ('BASE') then 'Basic'
     when group_descr in ('VALUES') then 'Valuable'
     when group_descr in ('PREFERRENCE') then 'Preferr'
     else 'Other'
end as Class
from dbo.DEVICE_HIST a
where a.expired >= '2017-12-01' and a.EFFTV <'2017-12-31'

union

-- Jan 2018
select distinct  a.device_id ,201801 as month_id,
case when group_descr in ('BASE') then 'Basic'
     when group_descr in ('VALUES') then 'Valuable'
     when group_descr in ('PREFERRENCE') then 'Preferr'
     else 'Other'
end as Class
from dbo.DEVICE_HIST a
where a.expired >= '2018-01-01' and a.EFFTV <'2018-01-31'

这是每月运行一次,根据当月,我们需要从上个月开始3个月的数据 - 1,向后。 例如,如果在2月份运行,则应该从10月到12月运行,如果在3月运行,则需要从11月到1月。 这将基于当前月份,但有人可以帮我自动化吗?

需要当前月份并返回的东西 - 1然后再从那里开始3个月。 虽然日期计算并不复杂,但如何根据当前月份动态更改查询?

1 个答案:

答案 0 :(得分:1)

假设这是SQL SERVER 2005 +:

-- Oct 2017
select distinct  a.device_id
                ,CONCAT(CAST(YEAR(a.expired) AS varchar(4)),right('00'+CAST(MONTH(a.expired) AS nvarchar(2)), 2))  as month_id,
                case when group_descr in ('BASE') then 'Basic'
                     when group_descr in ('VALUES') then 'Valuable'
                     when group_descr in ('PREFERRENCE') then 'Preferr'
                     else 'Other'
                end as Class
from @test a
where CONVERT(date, a.expired) >= DATEADD(month, DATEDIFF(month, 0, convert(date, DATEADD(MONTH, -3, GETDATE()))), 0)