|
|
|||||||||
|
|||||||||
|
|||||||||
| |
||
| ||||||||||||||||||||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Query - General - Using IF in calculation statement
Hi,
I have a statement that is calculating days that an employee has been working for the company. This is the statement so far: Code:
(SELECT SUM(DATEDIFF(dd, EmpStart, EmpEnd)) AS Expr1
FROM dbo.Employment AS Employment_2
WHERE (dbo.STAFF.AppNo = AppNo)
GROUP BY AppNo) AS TimeServed
The bit I need help with is the DATEDIFF bit. It calculates OK if there is an end date. But if end date is null, OR end date is > today, it should use today's date for the calculation. So I tried something like this: Code:
SUM(DATEDIFF(dd, EmpStart, (IF EmpEnd IS NULL OR EmpEnd > GetDate() THEN GetDate() ELSE EmpEnd))) But it didn't work - please can anyone help? Many thanks |
|
#2
|
||||
|
||||
|
Hi,
This is not tested but you should be able to use ISNull to substitute the current date if the enddate is null: Code:
SELECT SUM(DATEDIFF(dd, EmpStart, ISNULL(EmpEnd, getDate()))) AS Expr1
FROM dbo.Employment AS Employment_2
WHERE (dbo.STAFF.AppNo = AppNo)
GROUP BY AppNo) AS TimeServed
|
|
#3
|
|||
|
|||
|
Quote:
Yes that did work, you're right. But I also need a bit of conditional code which says that if EmpEnd > Today, then use today's date; sometimes people have given notice, which creates an end date in the future. How could I include that? Many thanks indeed |
|
#4
|
||||
|
||||
|
You should be able to encorporate a case statement, not tested:
Code:
SELECT SUM(DATEDIFF(dd, EmpStart, (CASE WHEN DATEDIFF(day, getDate(), EmpEnd) >0 THEN
getDate() WHEN EmpEnd IS NULL THEN getDate() ELSE EmpEnd END) )) AS Expr1
FROM dbo.Employment AS Employment_2
WHERE (dbo.STAFF.AppNo = AppNo)
GROUP BY AppNo) AS TimeServed
|
|
#5
|
|||
|
|||
|
Quote:
Oh yes yes, it works, you're a total star. I did try a case statement but got it totally wrong. Many thanks indeed! |
|
#6
|
||||
|
||||
|
Quote:
You're welcome, I'm glad it helped!! ![]() |
![]() |
| Viewing: ASP Free Forums > Database > SQL Development > Query - General - Using IF in calculation statement |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|