|
|
|
Valued Member
      
Group: General Forum Members
Last Login: Monday, November 05, 2012 7:17 AM
Points: 54,
Visits: 136
|
|
I have a table Customer which has following columns
Custid,PersonId,Startdate,Enddate,name,age .......
For each person there can be multiple rows in the table customer depending on startdate and end date .I want to select one personid for each person from table customer,the one having maximum end date. Consider the following example for table Customer
CustId PersonId startdate Enddate Name age ...
100 1 01/12/2011 02/12/2011 person1
101 1 02/13/2011 04/14/2011 person1
102 2 02/11/2011 04/14/2011 person2
103 2 04/15/2011 05/12/2011 person2
My query should give me
101 1 02/13/2011 04/14/2011 person1
103 2 04/15/2011 05/12/2011 person2
Please provide some help as to how to form the query for such a scenario
Thanks in advance
|
|
|
|
|
SSC Eights!
      
Group: General Forum Members
Last Login: Thursday, November 15, 2012 8:38 AM
Points: 802,
Visits: 1,169
|
|
Something like this should work nicely
Select t.CustId ,t.PersonId ,t.startdate ,t.Enddate ,t.Name from ( Select CustId ,PersonId ,startdate ,Enddate ,Name ,ROW_NUMBER() OVER(PARTITION BY PersonId ORDER BY Enddate DESC) as rownum from table1 ) as t where t.rownum=1
Dan
If only I could snap my figures and have all the correct indexes apear and the buffer clean and.... Start day dream here.
|
|
|
|
|
SSCertifiable
       
Group: General Forum Members
Last Login: Today @ 6:04 AM
Points: 6,661,
Visits: 5,687
|
|
Another is to do an INNER JOIN to a subquery for the CustID and MAX(EndDate), joined on both fields.
A third method would be to put the above subquery into a CTE and join to the CTE.
Brandie Tarvin, MCITP Database Administrator, MCDBA, MCSA
Webpage: http://www.BrandieTarvin.net LiveJournal Blog: http://brandietarvin.livejournal.com/ On LinkedIn!, Google+, and Twitter.
Freelance Writer: Shadowrun Latchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.
|
|
|
|
|
Valued Member
      
Group: General Forum Members
Last Login: Monday, November 05, 2012 7:17 AM
Points: 54,
Visits: 136
|
|
|
|
|
|
SSCoach
         
Group: General Forum Members
Last Login: Tuesday, May 21, 2013 1:55 PM
Points: 15,442,
Visits: 9,571
|
|
It looks to me like Customer and Person data need to be separated in this, to make it work well.
I'd be willing to be that "name" and "age" really belong in a "People" table.
Normalizing the data that way will make everything you do with it easier.
- Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC Property of The Thread
"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon
|
|
|
|