Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Finding the MIN and MAX date - How do I approach this?


Finding the MIN and MAX date - How do I approach this?

Author
Message
Luis Cazares
Luis Cazares
SSCrazy Eights
SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)SSCrazy Eights (8.6K reputation)

Group: General Forum Members
Points: 8590 Visits: 18174
Would this help?
WITH SampleData([EMPID],[EffectiveDate],[PrimaryRater], [PrimaryReviewer])
AS
( --This is sample data
SELECT '12345',convert(datetime,'10/10/2001'),'A12345', 'A67890' UNION ALL
SELECT '12345','07/12/2013','A12345', 'B67890' UNION ALL
SELECT '12345','08/18/2002','A12345', 'C67890' UNION ALL
SELECT '12345','07/17/1966','A12345', 'D67890' UNION ALL
SELECT '12345','01/01/1966','B12345', 'E67890'
)
--Solution starts here
,CTE AS(
SELECT EMPID,
PrimaryRater,
MIN( EffectiveDate) StartDate,
MAX( EffectiveDate) EndDate,
DENSE_RANK() OVER( PARTITION BY EMPID ORDER BY Min(EffectiveDate)) RN
FROM SampleData
GROUP BY EMPID,
PrimaryRater
)
SELECT c.EMPID,
c.StartDate,
c.PrimaryRater,
s.PrimaryReviewer,
ISNULL( c2.StartDate, GETDATE()) EndDate
FROM CTE c
JOIN SampleData s ON c.EMPID = s.EMPID
AND c.PrimaryRater = s.PrimaryRater
AND c.EndDate = s.EffectiveDate
LEFT
JOIN CTE c2 ON c.EMPID = c2.EMPID
AND c.RN = c2.RN - 1




Luis C.
General Disclaimer:
Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?


How to post data/code on a forum to get the best help: Option 1 / Option 2
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search