Quantcast
Viewing all articles
Browse latest Browse all 6

Which row do you want?

Top 1 does not make sense without order by, you will just get a random row, which might or might not be the first row you entered.Here I select the least (alfabetic) country per personSELECT A.Name, B.CountryFROM TABLE1 AINNER JOIN (SELECT IDadd,MIN(Name) Name FROM TABLE2 GROUP BY IDadd) AS BON B.IDadd = A.IDIt could also simply beSELECT ID,MIN(COUNTRY) FROM TABLE1 ALEFT JOIN TABLE2 B ON A.ID=B.IDaddGROUP BY IDBut it will get tedious with more columns in A, as you have to GROUP BY every column in A, you want to display, and will not work if there are more columns in B you want to show (and you want all B's to come from the same row for each A)If table2 had several rows per row in table1, and had several columns, likeIDadd todate Country address1001 01-feb-2010 US Hollywood Boulevard1001 10-jul-2009 UK Pinewood1002 03-apr-2012 DE Alexanderplatz1002 25-may-2008 FR ParisYou first find the (id,date) pairs, and then select the matching rows.SELECT A.name,B.todate,B.Country,B.addressFROM table1 ALEFT JOIN table2 B on A.ID=B.IDaddLEFT JOIN(SELECT IDadd,max(todate) todate FROM table2 WHERE todate='01-jan-2012' GROUP BY todate) AS Latest_Move ON B.IDadd=Latest_Move.IDadd AND B.todate=Latest_Move.todateThis would get where the persons were living 01-jan-2012Sam 01-feb-2010 US Hollywood BoulevardBill 25-may-2008 FR ParisBills move to Germany is not listed, because it is after 01-jan-2012

Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>