我目前有这个WHERE
子句,其中包含以下参数。
WHERE
Project ID=110
AND ((CAST(saa.Date AS DATE) >= '09/24/2014' AND CAST(saa.Date AS DATE) <= '09/24/2014') OR saa.Date IS NULL))
这里棘手的部分是saa.Date is NULL
部分将在所有日期中提取所有Null
值(这是过多的)我只想使用{{1的以下日期范围值
Null
所以我试图找出如何创建(
(CAST(sa.StartDateTime AS DATE) >= '09/24/2014' AND CAST(sa.StartDateTime AS DATE) <= '09/24/2014')
OR
(CAST(sa.EndDateTime AS DATE) >= '09/24/2014' AND CAST(sa.EndDateTime AS DATE) <= '09/24/2014')
)
语句,它可以像IF saa.Date是NULL然后[使用上面的日期范围参数]
答案 0 :(得分:2)
我的答案基于@ AHiggins,但增加了性能和可读性
- 避免cast
WHERE
ProjectID=110 AND
(
(
saa.Date between '09/24/2014 00:00:00.000' AND '09/24/2014 23:59:59.999'
) OR
(
saa.Date IS NULL AND
(
sa.StartDateTime between '09/24/2014 00:00:00.000' AND '09/24/2014 23:59:59.999'
) OR
(
sa.EndDateTime between '09/24/2014 00:00:00.000' AND '09/24/2014 23:59:59.999'
)
)
)
确保您在日期列上有索引
答案 1 :(得分:1)
如果我正确阅读它,你应该能够用布尔逻辑和几百万括号来做到这一点:
编辑:在关于@ horaciux回答的评论中注意到存在问题,意识到我们实际上需要更多的括号。我借用了借来的代码,并在下面添加了额外内容。WHERE
ProjectID=110 AND
(
(
saa.Date between '09/24/2014 00:00:00.000' AND '09/24/2014 23:59:59.999'
) OR
(
saa.Date IS NULL AND
( -- need to wrap the next two conditions in a single set of parentheses
(
sa.StartDateTime between '09/24/2014 00:00:00.000' AND '09/24/2014 23:59:59.999'
) OR
(
sa.EndDateTime between '09/24/2014 00:00:00.000' AND '09/24/2014 23:59:59.999'
)
)
)
)
答案 2 :(得分:1)
你知道吗
>= '09/24/2014'
AND <= '09/24/2014'
与...相同 = '09 / 24/2014'
where ProjectID=110
AND CAST(saa.Date AS DATE) = '09/24/2014'
OR (
saa.Date IS NULL
AND
(
CAST(sa.StartDateTime AS DATE) = '09/24/2014'
OR
CAST(sa.EndDateTime AS DATE) = '09/24/2014'
)
)
这比演员效率更高:
DATEADD(dd, DATEDIFF(dd, 0, COL),0)
但Horaciux的答案更有效率
答案 3 :(得分:0)
试试这个
(
(CAST(ISNULL(sa.StartDateTime, '09/24/2014') AS DATE) >= '09/24/2014' AND CAST(ISNULL(saa.StartDateTime, '09/24/2014') AS DATE) <= '09/24/2014')
)