我想根据两个日期时间是否共享来比较两个日期时间。 这有效:
SELECT *
FROM XXX
WHERE CAST(LoadDateLAG AS DATE) = CAST(LoadDateLEAD AS DATE)
但是,我实际上希望将结果作为额外的一列:
SELECT
CAST(LoadDateLAG AS DATE) = CAST(LoadDateLEAD AS DATE)
, *
FROM XXX
后者不起作用,因为SQLServer抱怨语法无效。 有什么建议吗?
结果应如下:
LoadDateLAG | LoadDateLEAD | (LoadDateLAG = LoadDateLEAD) [as bit]
我需要此功能来压缩历史表 -删除不必要的条目(例如,每天仅保留最后一个条目)。
答案 0 :(得分:3)
SQL Server 2012 +
SELECT IIF(CAST(LoadDateLAG AS DATE) = CAST(LoadDateLEAD AS DATE),1,0),* FROM XXX
答案 1 :(得分:1)
您可以使用CASE WHEN
:
SELECT
LoadDateLAG, LoadDateLEAD,
CASE WHEN CAST(LoadDateLAG AS DATE) = CAST(LoadDateLEAD AS DATE) THEN 1 ELSE 0 END AS isDateEquals
FROM XXX
-- WHERE CAST(LoadDateLAG AS DATE) = CAST(LoadDateLEAD AS DATE)
如果您还想显示DATE
值(而不是DATETIME)
,则可以使用以下SELECT
:
SELECT
CAST(LoadDateLAG AS DATE) AS LoadDateLAG,
CAST(LoadDateLEAD AS DATE) AS LoadDateLEAD,
CASE WHEN CAST(LoadDateLAG AS DATE) = CAST(LoadDateLEAD AS DATE) THEN 1 ELSE 0 END AS isDateEquals
FROM XXX
-- WHERE CAST(LoadDateLAG AS DATE) = CAST(LoadDateLEAD AS DATE)
如果要显示等于的DATE
值(而不是1或0),则可以使用以下SELECT
:
SELECT
LoadDateLAG, LoadDateLEAD,
CASE WHEN CAST(LoadDateLAG AS DATE) = CAST(LoadDateLEAD AS DATE) THEN CAST(LoadDateLAG AS DATE) ELSE NULL END AS equalsDate
FROM XXX
-- WHERE CAST(LoadDateLAG AS DATE) = CAST(LoadDateLEAD AS DATE)