sql每隔三天更新一次

时间:2017-12-20 11:50:45

标签: sql sql-update

嗨我有一张结果临时表,其中包含到达日期和出发日期,我需要在到达和离开之间每隔三天更新一次。 这是我的输出

output

我能想到的唯一方法是使用DATEADD为3的倍数,但到达和离开之间的天数可能是几个月甚至几年,所以我需要每隔三天设置一次更新,无论多少天

UPDATE #Report SET "Service" = CASE
    WHEN Date = DATEADD(DAY,3,CAST(FLOOR(CAST(Arr AS money)) AS Datetime)) THEN 'Full Service'
    WHEN Date = DATEADD(DAY,6,CAST(FLOOR(CAST(Arr AS money)) AS Datetime)) THEN 'Full Service'
    WHEN Date = DATEADD(DAY,9,CAST(FLOOR(CAST(Arr AS money)) AS Datetime)) THEN 'Full Service'
    WHEN Date = DATEADD(DAY,12,CAST(FLOOR(CAST(Arr AS money)) AS Datetime)) THEN 'Full Service'
    WHEN Date = DATEADD(DAY,15,CAST(FLOOR(CAST(Arr AS money)) AS Datetime)) THEN 'Full Service'
    WHEN Date = DATEADD(DAY,18,CAST(FLOOR(CAST(Arr AS money)) AS Datetime)) THEN 'Full Service'
    WHEN Date = DATEADD(DAY,21,CAST(FLOOR(CAST(Arr AS money)) AS Datetime)) THEN 'Full Service'
...
etc
ELSE 'Restricted Service' END

有人能想到解决方案吗?

2 个答案:

答案 0 :(得分:2)

我希望这样的事情:

UPDATE #Report
    SET Service = (CASE WHEN DATEDIFF(day, Arr, Date) % 3 = 0
                        THEN 'Full Service'
                        ELSE 'Restricted Service'
                   END);

我无法理解在您的查询版本中转换为money的行为。

答案 1 :(得分:0)

我找到了一个解决方案:

在源表中添加了一个Rank

RANK() OVER (PARTITION BY RoomID ORDER BY Date) AS Ranking

Divided rank by 3

UPDATE #x SET Ranking2 = CAST(Ranking AS DECIMAL(20,2))/3 

Update only where this is a whole number

UPDATE #Report SET "Service" = 
    CASE WHEN FS.Ranking2 = ROUND(FS.Ranking2, 0) THEN 'Full Service'
    ELSE 'Restricted Service' END

如果有更好的方法,请告诉我,但是