Search code examples
joindistinctrelation

Distinct join between 2 tables


enter image description here
this is my code :
SELECT DISTINCT Emps.name, Degrees.Name AS degree, Degrees.Date AS degree_date
FROM Emps INNER JOIN Degrees ON Emps.id = Degrees.empId
but distict dosn't work , i want this result
enter image description here


i want distict name with degree which has max id or max date


Solution

  • thanks for all i found the solution

    SELECT e.name, d.Name AS degree
    FROM Emps AS e
    full JOIN (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY t.empId ORDER BY t.id DESC) AS rn FROM Degrees AS t
    ) AS d ON e.id = d.empId
    WHERE d.rn = 1