具有工作日的DatePart包含在子句中

时间:2017-06-19 19:28:31

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

以下声明如何在内部工作?

DATEPART(WEEKDAY, CAL.DAY) in (1,7) then 0

我试过运行这个但是给了我错误,如果我删除了in子句那么它工作正常。

这是完整的代码:

SELECT CAL.DAY AS DATE
    ,FISCAL_PERIOD DATEPART(year, CAL.DAY)
    ,CASE 
        WHEN DATEPART(month, CAL.DAY) = 1
            AND DATEPART(day, CAL.DAY) = 1
            THEN 0
        WHEN DATEPART(month, CAL.DAY) = 1
            AND DATEPART(day, CAL.DAY) = 2
            AND DATEPART(WEEKDAY, CAL.DAY) IN (
                1
                ,7
                )
            THEN 0
        WHEN DATEPART(month, CAL.DAY) = 1
            AND DATEPART(day, CAL.DAY) = 3
            AND DATEPART(WEEKDAY, CAL.DAY) IN (
                1
                ,7
                )
            THEN 0
        ELSE NULL
        END AS BUSINESS_DAY_OVERRIDE
    ,
INTO #Demo
FROM CAL

1 个答案:

答案 0 :(得分:0)

DATEPART(WEEKDAY, ...)返回表示一周周期的整数1到7,将其与IN(1,7)进行比较没有错误

在达到该案例表达式之前存在语法问题。如果(例如)我假设在&#34之后有一个相等的符号; FISCAL_PERIOD ="然后语法很好。 (或者,也许相同的符号应该是逗号?)

SELECT cal.day AS [DATE], 
       FISCAL_PERIOD = Datepart(year, cal.day), 
       CASE 
         WHEN Datepart(month, cal.day) = 1 
              AND Datepart(day, cal.day) = 1 THEN 0 
         WHEN Datepart(month, cal.day) = 1 
              AND Datepart(day, cal.day) = 2 
              AND Datepart(weekday, cal.day) IN ( 1, 7 ) THEN 0 
         WHEN Datepart(month, cal.day) = 1 
              AND Datepart(day, cal.day) = 3 
              AND Datepart(weekday, cal.day) IN ( 1, 7 ) THEN 0 
         ELSE NULL 
       END     AS BUSINESS_DAY_OVERRIDE 
FROM   cal 

小心使用" date"作为列名,它也是一个TSQL关键字。我个人不建议将其用作列名。