SQL计数日期时间

时间:2015-06-13 10:42:52

标签: sql count concatenation

我必须连接两个字段的日期和时间部分,我已经设法做了,然后我需要测试结果是否< 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作为无效的列名称出现。如何才能使此查询生效?我需要子查询吗?

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

是的,你需要子查询:

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'