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 |
|
Richard Branson
Yak Posting Veteran
84 Posts |
Posted - 2005-03-01 : 07:57:56
|
| Hi Fellow Code WarriorsI was wondering how one could do the following:I have a table that has the following data:Ent_Nbr DateEn1 23/05/2004En1 25/07/2004En1 05/08/2004En1 03/12/2004EN2 03/01/2004EN2 18/09/2004EN2 23/05/2004EN4 29/04/2004EN4 03/12/2004EN4 21/04/2004EN4 05/08/2004EN4 23/05/2004EN4 26/09/2004What method can I use to select the latest and the the second latest date?Ent_Nbr Latest DateEnt_Nbr Second Latest DateFor each ent_nbrYou can't teach an old mouse new clicks. |
|
|
robvolk
Most Valuable Yak
15732 Posts |
|
|
Richard Branson
Yak Posting Veteran
84 Posts |
Posted - 2005-03-01 : 08:26:38
|
| Machine froze during submit processYou can't teach an old mouse new clicks. |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2005-03-01 : 09:14:28
|
| Try thisSelect Top 2 * from Table group by Ent_Nbr, Date order by Date DescMadhivananFailing to plan is Planning to fail |
 |
|
|
X002548
Not Just a Number
15586 Posts |
Posted - 2005-03-01 : 13:24:33
|
| [code]USE NorthwindGOSET NOCOUNT ONCREATE TABLE myTable99(Ent_Nbr char(3), [Date] datetime)GOSET DATEFORMAT dmyGOINSERT INTO myTable99(Ent_Nbr, [Date])SELECT 'En1', '23/05/2004' UNION ALLSELECT 'En1', '25/07/2004' UNION ALLSELECT 'En1', '05/08/2004' UNION ALLSELECT 'En1', '03/12/2004' UNION ALLSELECT 'EN2', '03/01/2004' UNION ALLSELECT 'EN2', '18/09/2004' UNION ALLSELECT 'EN2', '23/05/2004' UNION ALLSELECT 'EN4', '29/04/2004' UNION ALLSELECT 'EN4', '03/12/2004' UNION ALLSELECT 'EN4', '21/04/2004' UNION ALLSELECT 'EN4', '05/08/2004' UNION ALLSELECT 'EN4', '23/05/2004' UNION ALLSELECT 'EN4', '26/09/2004'GO SELECT Ent_Nbr, 'MAX_Date-0' AS DateType, MAX([Date]) AS MAX_Date FROM myTable99 GROUP BY Ent_NbrUNION ALL SELECT Ent_Nbr, 'MAX_Date-1' AS DateType, MAX([Date]) AS MAX_Date FROM myTable99 o WHERE [Date] < (SELECT MAX([Date]) FROM myTable99 i WHERE o.Ent_Nbr = i.Ent_Nbr) GROUP BY Ent_NbrORDER BY Ent_Nbr, 3 DESCGOSET DATEFORMAT mdySET NOCOUNT OFFDROP TABLE myTable99GO[/code]Brett8-) |
 |
|
|
Richard Branson
Yak Posting Veteran
84 Posts |
Posted - 2005-03-02 : 01:22:02
|
| Thanks a million Brett - the solution is perfect and pretty fastYou can't teach an old mouse new clicks. |
 |
|
|
|
|
|
|
|