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 |
huub
Starting Member
4 Posts |
Posted - 2014-10-17 : 11:15:41
|
HOW TO SELECT LAST ROW IN GROUP BY CLAUSE AND JOIN LAST ROW WITH ANOTHER TABLE IN ONE QUERY?INPUT:custid livingstatus date1 single 2014-01-01 00:00:00.0001 married 2014-01-02 00:00:00.0001 married_kids 2014-01-03 00:00:00.0002 married_kids 2014-01-04 00:00:00.0002 married 2014-01-05 00:00:00.0002 single 2014-01-06 00:00:00.000Query 1 -- select last recordSELECT *FROM(SELECT ROW_NUMBER() OVER(PARTITION BY Custid ORDER BY Date DESC) AS Seq,*FROM Living_Situation)tWHERE Seq=1Output:Seq custid livingstatus date1 1 married_kids 2014-01-03 00:00:00.0001 2 single 2014-01-06 00:00:00.000Table Customer:custid sexe surname1 m jansen2 m pietersenHow to link Query 1 with table Customer in one query?: Desired output in ONE query:custid sexe surname livingstatus1 m jansen married_kids2 m pietersen single |
|
tkizer
Almighty SQL Goddess
38200 Posts |
Posted - 2014-10-17 : 11:46:23
|
[code]SELECT ot.custid, ot.sexe, ot.surname, t.livingstatusFROM( SELECT ROW_NUMBER() OVER(PARTITION BY Custid ORDER BY Date DESC) AS Seq, * FROM Living_Situation) tJOIN OtherTable ot ON t.custid = ot.custidWHERE t.Seq=1[/code]Tara KizerSQL Server MVP since 2007http://weblogs.sqlteam.com/tarad/ |
|
|
huub
Starting Member
4 Posts |
Posted - 2014-10-18 : 09:10:08
|
Hi Tara,I am very happy with your quick reply. Yes it works. Thank you very much! Regards,Huub Cremers, Amstelveen (near Amsterdam), Netherlands |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
|
|
|
|