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 |
happyslug
Starting Member
5 Posts |
Posted - 2013-07-25 : 06:33:27
|
I have tables to represent client and courseclient------id intclientname varchar(50)course------id intcoursename varchar(50)coursedate datetimeEach client may attend one or more course - so I have the following tableclientcourse------------id intclientid intcourseid intI want a select statement to give me the last course based on course date for each client so if we hadclient------ id clientname 1 Tom 2 Dick 3 Harrycourse------ id coursename coursedate 1 English 1-jan-2013 2 Science 1-mar-2013 3 Maths 1-feb-2013Clientcourse------------ id clientid courseid 1 1 1 2 1 3 3 2 1 4 3 2 5 3 3 I want to return clientid courseid 1 3 2 1 3 2I think I could work this out myself using rank, but is there an easier way? |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-07-25 : 06:44:37
|
[code]SELECT clientid,courseidFROM(SELECT cl.clientid,cr.courseid,ROW_NUMBER() OVER (PARTITION BY clientid ORDER BY cr.coursedate DESC) AS SeqFROM client clINNER JOIN Clientcourse ccON cc.clientid = cl.clientid INNER JOIN course crON cr.id = cc.courseid)tWHERE Seq=1[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
happyslug
Starting Member
5 Posts |
Posted - 2013-07-30 : 04:57:42
|
Thanks visakh16This is similar to how I would do it with rank - I guess ROW_NUMBER is similar. |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-07-30 : 05:10:38
|
Not exactly. Rank will return same value for all the rows with same value of coursedate. RowNumber will just randomly number them as 1,2,3 etc even if value is same.------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
happyslug
Starting Member
5 Posts |
Posted - 2013-08-01 : 07:14:47
|
OK - thanks again.I've just used this again on a different project. |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-08-01 : 07:38:16
|
coolglad that I could be of help to you------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
|
|
|