如何在三个table中加入一对多不同的?

How to join one to many distinct in three table?

我有三个table我想加入

Table: 学生

  ID  Fname Lname 
--------------------------------
  1    Jhon gates

Table: 注册信息

 ID   RegisterDate  StudentID_FK ClassID_FK
----------------------------------------------------
  1    2013/08/05      1             1
  2    2014/08/06      1             2
  2    2015/08/07      1             3

Table: Class

 ID   ClassName
--------------------
 1     Class1
 2     Class2
 2     Class3

期望输出

 ID  Fname  Lname  ClassName 
--------------------------------
  1   Jhon  gates    Class3

我只需要学生信息和最后class姓名

我试过:

  Select DISTINCT [S].Fname, [S].Lname ,[C].ClassName
   FROM Registration as R 
   INNER JOIN  Student as [S] on [S].ID=[R].StudentID_FK
   INNER JOIN   Class  as[c] on [C].ID=[R].ClassID_FK

但这会显示所有 class 姓名

 ID  Fname  Lname  ClassName   
--------------------------------
  1   Jhon  gates    Class1  
  2   Jhon  gates    Class2  
  3   Jhon  gates    Class2  

这应该有效:

Select s.ID,s.Fname,s.Lname,c.ClassName from student s inner join RegistrationInfo r on s.Id= r.StudentID_FK inner join Class c on c.Id=r.ClassID_FK

我相信这就是您要找的。在这里,我使用 ROW_NUMBER 窗口函数为每个条目分配一个行号,按学生分区,按日期 DESC 排序——所以最近的日期是 RID=1.

;WITH LastClass 
AS
(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY R.StudentID_FK ORDER BY R.RegisterDate DESC) AS RID
    FROM Registration R
)

SELECT S.id, S.Fname, S.Lname, C.ClassName
FROM LastClass R
JOIN Student S ON R.StudentID_FK=S.id
JOIN Class C ON R.ClassID_FK=C.id 
WHERE RID=1

工作样本:

DECLARE @Student TABLE (id int, Fname varchar(25), Lname varchar(25))
DECLARE @RegistrationInfo TABLE (id int, RegisterDate DATETIME, StudentID_FK int, ClassID_FK int)
DECLARE @Class TABLE (id int, ClassName varchar(25))

INSERT INTO @Student (id, Fname, Lname)
SELECT 1,'Jhon','gates' UNION ALL
SELECT 2,'Bill','gates'

INSERT INTO @RegistrationInfo (id, RegisterDate, StudentID_FK, ClassID_FK)
SELECT 1,'2013/08/05',1,1 UNION ALL
SELECT 2,'2014/08/06',1,2 UNION ALL
SELECT 3,'2015/08/07',1,3 UNION ALL
SELECT 4,'2015/01/04',2,1 UNION ALL
SELECT 5,'2015/03/05',2,3

INSERT INTO @Class (id, ClassName)
SELECT 1, 'Class1' UNION ALL
SELECT 2, 'Class2' UNION ALL
SELECT 3, 'Class3'

;WITH LastClass 
AS
(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY R.StudentID_FK ORDER BY R.RegisterDate DESC) AS RID
    FROM @RegistrationInfo R
)

SELECT S.id, S.Fname, S.Lname, C.ClassName
FROM LastClass R
JOIN @Student S ON R.StudentID_FK=S.id
JOIN @Class C ON R.ClassID_FK=C.id 
WHERE RID=1

T-SQL:

SELECT 
            TOP 1
             S.Fname
            ,S.LName
            ,C.ClassName
            ,R.RegisterDate  
    FROM tblStudents AS S
    LEFT JOIN tblRegistration AS R ON S.ID = R.StudentID_FK 
    LEFT JOIN tblClasses AS C ON C.ID = R.ClassID_FK
    WHERE S.ID = 1

    ORDER BY R.RegisterDate DESC