SQL Server 2005:如何减去 6 个月

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3932947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:56:20  来源:igfitidea点击:

SQL Server 2005: how to subtract 6 month

sqlsql-server-2005datetimedatedatediff

提问by skaeff

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 开始。

回答by Alex Bagnolini

You can use DATEADD:

您可以使用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))

回答by skaeff

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).

我需要根据条件选择算法 - 如果两个日期之间的天数与 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