0

我在系统中有策略

PolRef       Start            End
POL123     22/11/2012      23/12/2014
POL212     24/09/2012      23/10/2012
POL214     23/08/2012      29/09/2012

我要求用户提供报告日期,用户输入 24/10/2012 这变成@StartDate

由此我得出季度按月计算:

set @currentMonth = Month(@StartDate)

if @currentMonth = 1 or @currentMonth = 2 or @currentMonth = 3 begin set @startmonth = 1 set @endmonth = 3 end

if @currentMonth = 4 or @currentMonth = 5 or @currentMonth = 6 begin set @startmonth = 4 set @endmonth = 6 end

if @currentMonth = 7 or @currentMonth = 8 or @currentMonth = 9 begin set @startmonth = 7 set @endmonth = 9 end

if @currentMonth = 10 or @currentMonth = 11 or @currentMonth = 12 begin set @startmonth = 10 set @endmonth = 12 end

然后我得到一个日期范围:

@quarterStartDate = CAST(CAST(YEAR(@StartDate) AS varchar) + '-' + CAST(@startMonth AS varchar) + '-' + '01') AS Date)

@quarterEndDate = CAST(CAST(YEAR(@EcdDate) AS varchar) + '-' + CAST(@endMonth AS varchar) + '-' + '31') AS Date)

这将给我 01-10-2012 和 31-12-2012。基本上我需要一个脚本来仅恢复本季度的政策。该政策不必跨越整个季度日期范围,只需存在于季度日期范围内。

预期的结果是

PolRef       Start            End
POL123     22/11/2012      23/12/2014
POL212     24/09/2012      23/10/2012

出现 Pol123 是因为它跨越了季度日期范围。Pol212 存在是因为它在该季度日期范围内到期。Pol214 没有出现,因为它既没有跨越、过期也没有在本季度开始。

任何帮助将不胜感激

4

4 回答 4

3
Select *
  From policies
 Where Start <= @quarterEndDate
   And @quarterStartDate <= [End]

如果两个开始都在另一个结束之前,那么你有一个重叠(即存在于四分之一)

但是,我会删除变量并使用这个更准确的范围:

Select *
  From policies
 Where Start < dateadd(q,1+datediff(q,0,getdate()),0)
   And dateadd(q,datediff(q,0,getdate()),0) <= [End]
于 2012-10-25T10:59:43.653 回答
0

你可以试试这个

select * from policies where start>=@quarterStartDate
 and end<=@quarterenddate
于 2012-10-25T10:57:37.933 回答
0
select *
from policies
where 
    [Start] <= @quarterEndDate and
    [End] >= @quarterStartDate

要查找季度的开始和结束,您可以使用

declare @date datetime, @quarterStartDate datetime, @quarterEndDate datetime

select @date = convert(datetime, convert(nvarchar(8), getdate(), 112), 112)

select @quarterStartDate = dateadd(qq, datepart(qq, @date) - 1, dateadd(dd, -datepart(dy, @date) + 1, @date))
select @quarterEndDate = dateadd(dd, -1, dateadd(mm, 3, @quarterStartDate))
于 2012-10-25T10:57:56.613 回答
0

如果 startdate 和 enddate 是日期,而不是日期时间...

Select * 
from policies 
where StartDate<=@quarterenddate
and EndDate>=@quarterstartdate

您可能还会发现datepart(q,getdate())有用。

计算季度开始和结束日期

select @quarterstartdate = convert(varchar(4),year(@d))+'-' + CONVERT(varchar(2),(DATEPART(Q,@d))*3-2)+'-1',
       @quarterenddate= dateadd(day,-1,DATEADD(month,3, @quarterstartdate))
于 2012-10-25T10:57:57.840 回答