0

我要加入三张桌子

表:学生

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

表:注册信息

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

表:类

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

期望的输出

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

我只需要学生信息姓氏

我试过:

  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

但这会显示所有类名

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

3 回答 3

0

这应该有效:

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
于 2015-08-07T15:23:00.020 回答
0

我相信这就是你要找的。在这里,我使用ROW_NUMBER窗口函数为每个条目分配一个 row#,由 Student 分区,按日期排序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
于 2015-08-07T15:31:36.257 回答
0

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
于 2015-08-07T15:32:04.313 回答