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.
| Author |
Topic |
|
bluemetal
Starting Member
26 Posts |
Posted - 2005-08-17 : 01:37:27
|
| Hi Guys:Consider the following Sample Table:POL ID DATE001 1 21/05/2005001 3 25/05/2005002 4 30/05/2005002 5 02/06/2005002 8 10/06/2005003 9 12/06/2005Can i do a Query that returns me a result with each of these rows and the row with the next maximum date? (Grouped by POL) ... Something like this:POL ID DATE ID DATE001 1 21/05/2005 3 25/05/2005 001 3 25/05/2005 3 002 4 30/05/2005 5 02/06/2005 002 5 02/06/2005 8 10/06/2005 002 8 10/06/2005 |
|
|
mmarovic
Aged Yak Warrior
518 Posts |
Posted - 2005-08-17 : 02:10:19
|
| [code]select a.pol, max(a.date)from sampleTable ajoin (Select b.pol, max(b.date) as maxDate from SampleTable b group by b.pol) as gb on a.pol = gb.polwhere a.date < gb.Date[/code]This query needs work for pols with just one date, but I have to go now. If no one fix it until I come back, I'll do it later. |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2005-08-17 : 02:21:07
|
Try this alsoSelect *, (select top 1 id from yourtable where pol=T.pol and date>T.date) as MaxId, (select top 1 date from yourtable where pol=T.pol and date>T.date) as MaxDate from yourtable T MadhivananFailing to plan is Planning to fail |
 |
|
|
mmarovic
Aged Yak Warrior
518 Posts |
Posted - 2005-08-18 : 06:11:19
|
| Ok, my query can be improved using outer join, but the question is how do you want to handle duplicates, I mean when more then one row for the same pol reaches the same max date value. |
 |
|
|
|
|
|