SQL Server 2005:如何减去6个月

时间:2022-10-07 01:30:52

I have a date, suppose today date

我有个约会,假设是今天

declare @d datetime
set @d = '20101014'

I need

我需要

select @d - <six month>

where is the real number of days that contains last six month, beginning from @d.

从@d开始,包含6个月的实际天数。

2 个解决方案

#1


42  

You can use DATEADD:

您可以使用返回:

select DATEADD(month, -6, @d)

EDIT: if you need the number of days up to 6 months ago you can use DATEDIFF:

编辑:如果你需要6个月前的天数,你可以使用DATEDIFF:

select DATEDIFF(day, @d, DATEADD(month, -6, @d))

#2


1  

Also check this up (developing this theme):

也检查一下(开发这个主题):

i need to choose the algorythm depending on the condition - if there are as many days between two dates as in 6 month (ago from the last date).

我需要根据情况选择algorythm——如果两个日期之间的天数与6个月的天数相同(从最后一个日期开始)。

I did it in this way:

我这样做了:

    case
      when
        DATEDIFF(day, DATEADD(month, -6, @pDateEnd), @pDateEnd)
        >
        DATEDIFF(day, @pDateBegin, @pDateEnd)
      then 'there is no 6-month difference between two dates'
      else 'there is 6-month difference ore more between two dates'
    end

#1


42  

You can use DATEADD:

您可以使用返回:

select DATEADD(month, -6, @d)

EDIT: if you need the number of days up to 6 months ago you can use DATEDIFF:

编辑:如果你需要6个月前的天数,你可以使用DATEDIFF:

select DATEDIFF(day, @d, DATEADD(month, -6, @d))

#2


1  

Also check this up (developing this theme):

也检查一下(开发这个主题):

i need to choose the algorythm depending on the condition - if there are as many days between two dates as in 6 month (ago from the last date).

我需要根据情况选择algorythm——如果两个日期之间的天数与6个月的天数相同(从最后一个日期开始)。

I did it in this way:

我这样做了:

    case
      when
        DATEDIFF(day, DATEADD(month, -6, @pDateEnd), @pDateEnd)
        >
        DATEDIFF(day, @pDateBegin, @pDateEnd)
      then 'there is no 6-month difference between two dates'
      else 'there is 6-month difference ore more between two dates'
    end