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 |
sarblota
Starting Member
8 Posts |
Posted - 2008-10-16 : 04:03:53
|
HiHave a table as follows (truncated for simplicity):Key dateP1 1/1/06P1 15/2/07P1 13/2/08P2 1/1/05What I want to do is to return each P1 with the previous highest date.So the return would look like.Key Date LastDateP1 13/2/08 15/2/07P1 15/2/07 1/1/06P1 1/1/06 NULLP2 1/1/05 NULLand so on.Trying all sorts to no avail! cheersSarb Lota |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-10-16 : 04:09:43
|
[code]SELECT t.Key,t.date,prev.dateFROM Table tOUTER APPLY (SELECT TOP 1 date FROM Table WHERE Key=t.Key AND date <t.date ORDER BY date DESC)prev[/code] |
|
|
sarblota
Starting Member
8 Posts |
Posted - 2008-10-16 : 04:14:38
|
Sorry all!Just remembered that I'm using sql server 2000!!!cheersSarb Lota |
|
|
sarblota
Starting Member
8 Posts |
Posted - 2008-10-16 : 04:23:44
|
HI VisakhThanks for the prompt reponse.I've tried your code snippet with no luck. Is this 2005 specific SQL?cheersSarb Lota |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-10-16 : 04:25:20
|
quote: Originally posted by sarblota Sorry all!Just remembered that I'm using sql server 2000!!!cheersSarb Lota
then remember to post in correct forums in future. try the belowSELECT t1.key,t1.date,MAX(t2.date) AS prevdateFROM table t1INNER JOIN table t2ON t2.Key=t1.KeyAND t2.date<t1.dateGROUP BY t1.key,t1.date |
|
|
sarblota
Starting Member
8 Posts |
Posted - 2008-10-16 : 04:35:04
|
Thanks alot.First post so apologies for posting to the wrong forum!cheersSarb Lota |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-10-16 : 04:48:07
|
quote: Originally posted by sarblota Thanks alot.First post so apologies for posting to the wrong forum!cheersSarb Lota
No worries. You're welcome |
|
|
|
|
|