palum
palum

Reputation: 233

tsql-Joining tables with group by

Have 2 tables TableA

    StudentID   MeetingID  TeacherID   Date
     001         1002581    1056      10-12-2012
     001         1006789    1056      10-13-2012
     001         1006754    1058      10-13-1012

Have one more table B

     StudentID      MeetingID    TeacherID     Date        Value
         001          1002581      1056         10-12-201     15
         001          1002856      1056         10-20-2012    21

The conditions are max(date) of a particular student teacher meeting from table A matches the max(date) of the same student teacher meeting in table B with the value. I would like to see the resultset as something like

   StudentID       MeetingID     TeacherID     Date          Value
   001             1006789       1056          10-20-2012     21

How can i achieve the above resultset

Upvotes: 0

Views: 93

Answers (2)

Narsimha
Narsimha

Reputation: 184

SELECT TOP 1 c.StudentID,c.MeetingID,c.TeacherID,c.tab1_dates,c.VALUE
FROM 
(
    SELECT a.StudentID,a.MeetingID,a.TeacherID,a.Dates AS tab1_dates,b.Dates AS tab2_dates,b.VALUE,
    ROW_NUMBER() OVER (ORDER BY a.Dates,b.Dates) AS RN1
    FROM tab2 b
    INNER JOIN
    (
      SELECT StudentID,MeetingID,TeacherID,Dates FROM tab1
    ) a
    ON b.StudentID = a.StudentID
    AND b.TeacherID = a.TeacherID
        ) c
ORDER BY RN1 DESC

--SQL Fiddle - http://www.sqlfiddle.com/#!3/c6cea/1

Sorry, couldn't format well.

Upvotes: 1

Ryan Griggs
Ryan Griggs

Reputation: 2758

First, I'm curious why you have the same data in two separate tables instead of linking them via ID. I.e. Meetings -> Values

Per your requirements, this should work. This finds the most recent meeting which is present in both tables.

SELECT B.* 
FROM B INNER JOIN A ON B.StudentID = A.StudentID AND B.MeetingID = A.MeetingID AND B.Date = A.Date
WHERE B.Date = (SELECT MAX(Date) FROM A WHERE A.StudentID = B.StudentID AND A.MeetingID = B.MeetingID)

Here's the Fiddle: http://sqlfiddle.com/#!6/d15ca/4

Upvotes: 1

Related Questions