SQL 计算日期时间

SQL count date time

我必须连接两个字段的日期和时间部分,我已经设法做到了,然后我需要测试结果是否 < getdate()

select count(cast(cast(DischargeDatenew as date) as datetime) + cast(DischargeTime as time))as Requiredby FROM [dbo].[Main]
 where Location = 'Home' and ScriptTypeID = '1' and Requiredby < GETDATE()

不幸的是,第二个 Requiredby 作为无效的列名出现。我怎样才能让这个查询工作?我需要子查询吗?

是的,您将需要子查询:

select * from (select someExpression as Requiredby 
               FROM [dbo].[Main] 
               where Location = 'Home' and ScriptTypeID = '1') t 
where Requiredby < GETDATE()

但我真的认为你想要这个:

select sum(case when cast(cast(DischargeDatenew as date) as datetime) +
                     cast(DischargeTime as time) < getdate() then 1 
                     else 0 end) as Requiredby 
FROM [dbo].[Main] 
where Location = 'Home' and ScriptTypeID = '1'

您不需要 COUNT 中的计算,只需将其移至 WHERE:

select count(*) 
FROM [dbo].[Main]
where Location = 'Home' and ScriptTypeID = '1'
and cast(cast(DischargeDatenew as date) as datetime)
       + cast(DischargeTime as time) < GETDATE()