获取每年只有月份和日期的日期之间的日期范围

时间:2013-10-03 16:47:53

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

我需要在每年的7月1日到10月31日之间获得日期。基于此,我必须更新另一列。

日期字段是日期时间。应该是这样的:

Select Cash = Case When date between '1st July' and '31st October' Then (Cash * 2) End
From MytTable

注意:此范围应该适用于每一年。

4 个答案:

答案 0 :(得分:3)

这是一种方式:

SELECT Cash = CASE WHEN RIGHT(CONVERT(VARCHAR(8),[date],112),4) 
              BETWEEN '0701' AND '1031' THEN Cash*2
              ELSE Cash END --I added this 

答案 1 :(得分:2)

对于您的情况,您可以使用月份并确保它在7到10之间。

这是您的查询方式:

select Cash = case when month([Date]) in (7, 8, 9, 10) then (Cash * 2) else Cash end

select Cash = case when month([Date])  between 7 and 10 then (Cash * 2) else Cash end

答案 2 :(得分:1)

这个解决方案对我有用,可以获得一些按月计划重复安排的主题。它处理跨越多年,例如从11月1日到3月1日安排的项目。

我的数据存储方式如下:

ThemeName, StartMonth, StartDay, EndMonth, EndDay
Christmas, 12,1,12,26
Winter, 11, 1, 3, 1
Spring, 3,1,5,1
Sports, 0,0,0,0 //continuous

以下是查询:

    SELECT
         DISTINCT ThemeName
    FROM (
        SELECT 
            CASE WHEN EndDate < StartDate AND ((Current Between StartDate AND 1231) OR (Current Between 0101 AND EndDate) ) THEN -- span multiple year between dates
                ThemeName
            WHEN StartDate < EndDate AND Current Between StartDate AND EndDate THEN -- normal between dates
                ThemeName
            WHEN StartDate = 0 AND EndDate = 0 THEN -- continuous
                ThemeName
            ELSE
                'NG'
            END as ThemeName
        FROM (
                 SELECT
                         ThemeName, StartDate, EndDate, Current
                 FROM (     
                         SELECT
                             ThemeName,
                             CAST(Concat(LPAD(CONVERT(StartMonth , CHAR(2)),2,'0'), LPAD(CONVERT(StartDay , CHAR(2)),2,'0') ) as DECIMAL) as StartDate,
                             CAST(Concat(LPAD(CONVERT(EndMonth , CHAR(2)),2,'0'), LPAD(CONVERT(EndDay , CHAR(2)),2,'0') ) as DECIMAL) as EndDate,
                             CAST(Concat(LPAD(CONVERT(MONTH(CURRENT_DATE) , CHAR(2)),2,'0'), LPAD(CONVERT(DAY(CURRENT_DATE) , CHAR(2)),2,'0') ) as DECIMAL)  as current
                         FROM
                             companythemeschedules
                         WHERE
                             companyid = 221 
                 ) a

         ) b
    ) c
    WHERE
        ThemeName != 'NG'

答案 3 :(得分:0)

尝试这一个:

DECLARE @DT DATE = GETUTCDATE() , @START_DATE VARCHAR(10) = '07-01' , @END_DATE VARCHAR(10) = '10-31'
SELECT 
CASE 
    WHEN RIGHT(@DT,5) BETWEEN  @START_DATE AND  @END_DATE
    THEN
    (CASH * 2)
    ELSE
    'NO MATCH'
END AS CASH