复杂的IIF到SQL 2008

时间:2015-11-26 07:41:49

标签: sql-server sql-server-2008

您好我正在尝试复制我在MS Access中使用的复杂IIF函数,但似乎无法使用CASE将其转换为SLQ 2008。我正在尝试创建类似这样的WHERE子句

..... WHERE (IIF([Created Date]= NULL, IIF(DATEDIFF(day,[Created Date],[POSTED Date])<=3,1,IIF([Created Date] BETWEEN [Disti Reported Sales Date] AND [Posted Date]),1,NULL)))=1 AND ...... 基本上它的作用是从一列查看日期并将其与其他两列进行比较,但如果其中一列是NULL,则它使用不同的比较。

1 个答案:

答案 0 :(得分:1)

字面翻译应该看起来很接近:

WHERE (CASE
    WHEN [Created Date] IS NULL
    THEN (CASE
        WHEN DATEDIFF(DD, [Created Date], [POSTED Date]) <= 3 
        THEN 1
        ELSE (CASE
            WHEN [Created Date] BETWEEN [Disti Reported Sales Date] AND [Posted Date]
            THEN 1 
            ELSE 0
            END)
        END)
    ELSE 0
    END) = 1

但是,这可以简化为:

WHERE (CASE
    WHEN [Created Date] IS NULL AND DATEDIFF(DD, [Created Date], [POSTED Date]) <= 3 THEN 1
    WHEN [Created Date] IS NULL AND [Created Date] BETWEEN [Disti Reported Sales Date] AND [Posted Date] THEN 1
    ELSE 0 END) = 1

如我的评论中所述,如果[创建日期]为空,您仍尝试在任何计算中仍然使用它,这似乎仍然很奇怪。