Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I have a table of rate changes for different departments. This is table DeptRates with the following columns: ID int (unique row ID), DeptNo varchar(6), EffectDate smalldatetime, Rate decimal(7,2). Sample data for this table:
The EndingDate column is calculated as the day before the next EffectDate for the department. If there is no further EffectDate that follows, the EndingDate should be set to 12/31/9999.
I would greatly appreciate if someone could please give me an efficient query for doing this.
Thanks in advance!
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts
Posted - 2012-07-18 : 13:47:23
Assuming ID's are sequential and assuming that EffectDate is of type DATETIME, you can do the following.
SELECT a.Id, a.DeptNo, a.EffectDate, COALESCE(DATEADD(dd, -1, b.EffectDate),'99991231') AS EndingDate, Rate FROM DeptRates a LEFT JOIN DeptRates b ON a.ID+1 = b.ID;
jleitao
Posting Yak Master
100 Posts
Posted - 2012-07-18 : 13:51:57
If id is not sequential:
SELECT ID, DepNo, effectDate,
COALESCE( DATEADD(dd, -1, (select MIN(effectDate) FROM DeptRates T WHERE T.effectDate > A.effectDate and A.deptno = T.deptno) ) ,'99991231') as EndingDate, Rate FROM DeptRates A order by 1
mtl777
Yak Posting Veteran
63 Posts
Posted - 2012-07-18 : 15:54:03
Awesome! That was quick. Thanks everyone!
I chose jleitao's solution because the ID is not necessarily sequential.
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2012-07-18 : 16:31:10
quote:Originally posted by sunitabeck
Assuming ID's are sequential and assuming that EffectDate is of type DATETIME, you can do the following.
SELECT a.Id, a.DeptNo, a.EffectDate, COALESCE(DATEADD(dd, -1, b.EffectDate),'99991231') AS EndingDate, Rate FROM DeptRates a LEFT JOIN DeptRates b ON a.ID+1 = b.ID;
shouldnt it require DeptNo comparison also in join condition?
------------------------------------------------------------------------------------------------------ SQL Server MVP http://visakhm.blogspot.com/