SQL count date time

462 Views Asked by At

I have to concatenate the date and time portion of two fields, which I have managed to do, then I need to test if the result is < 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()

Unfortunately the second Requiredby comes up as an invalid column name. How can I get this query to work? Do I need a subquery?

2

There are 2 best solutions below

2
On BEST ANSWER

Yes you will need subquery:

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

But I really think you want this:

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'
0
On

You don't need the calculation in COUNT, simply move it to 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()