DatabasePrincess
MIS
SQL Server 2005 sp3
This is driving me nuts. It's probably a simple solution but I'm just not seeing it.
We have a table of employment records like this (simplified):
What I need to do is calculate the number of months where type is "reg". For example, the number of months for the first record is 13 (select datediff(mm,'2009-08-02','2010-09-12')). However, I still need to count the entire month of September for 2010. So I would add one to that result giving 14 months. (5 months for 2009 + 9 months for 2010)
I skip the next record where type is "leave".
For the next record where the throughDate is null, I use the current date. So select datediff(mm,'2010-09-26',getdate()) returns 1 month. I need to count the entire month of October which is the current month so I would add 1 to that result giving 2 months. The complete total number of months is now 16. If you add that up manually, it really should be 15.
Here's the problem. I need to make sure I don’t count the same month twice. So I need to somehow exclude counting September 2010 twice. Not every employee will have this situation.
Does this make sense? Any ideas how I can do this in one query or maybe two? Thanks!
This query returns 16 using the data above:
This is driving me nuts. It's probably a simple solution but I'm just not seeing it.
We have a table of employment records like this (simplified):
Code:
ID fromDate throughDate type
---- ---------- ----------- ----
1 2009-08-02 2010-09-12 reg
1 2010-09-13 2010-09-25 leave
1 2010-09-26 null reg
I skip the next record where type is "leave".
For the next record where the throughDate is null, I use the current date. So select datediff(mm,'2010-09-26',getdate()) returns 1 month. I need to count the entire month of October which is the current month so I would add 1 to that result giving 2 months. The complete total number of months is now 16. If you add that up manually, it really should be 15.
Here's the problem. I need to make sure I don’t count the same month twice. So I need to somehow exclude counting September 2010 twice. Not every employee will have this situation.
Does this make sense? Any ideas how I can do this in one query or maybe two? Thanks!
This query returns 16 using the data above:
Code:
Select sum(datediff(mm,fromDate,isnull(throughDate,getdate()))+1)
From tblEmployment
Where type = 'reg'