如何从 SQL 服务器中的 INNER JOIN 查询中获取 DISTINCT 行

How to get DISTINCT row from INNER JOIN Query in SQL Server

我一直在从事一个学校管理项目。一位老师有多个科目,我只需要在查询中显示一个科目,但我得到了一位老师拥有的所有科目。现在我只需要老师 2 的一条记录(TeacherId =2 在上面的屏幕截图查询中有两个科目(英语和数学)。英语或数学中的任何一个都可以。

文本查询:

SELECT        dbo.Teacher.TeacherId, dbo.Teacher.TeacherName, dbo.Gender.Gender, dbo.Teacher.DOB, ISNULL(dbo.Subject.Subject, 'No Subject') AS Subject, 
                         dbo.Teacher.Contact, dbo.Teacher.Address, dbo.Teacher.Email, dbo.Teacher.Photo
FROM            dbo.Subject INNER JOIN
                         dbo.TeacherSubject ON dbo.Subject.SubjectId = dbo.TeacherSubject.SubjectId RIGHT OUTER JOIN
                         dbo.Teacher INNER JOIN
                         dbo.Gender ON dbo.Teacher.Gender = dbo.Gender.GenderId ON dbo.TeacherSubject.TeacherId = dbo.Teacher.TeacherId

在此先感谢您对我的帮助。

使用不同的子句。这应该适合你。在您的情况下,Select 和 dbo.Teacher.TeacherId 之间的区别(在第一行)。

将您的查询添加 Row_Number() 语句作为另一列并将整个查询放入 CTE

WITH CTE AS
(
Select *,Row_Number()OVER(PARTITION BY SUBJECT ORDER BY 1 DESC)RN from Table
)
Select * from CTE WHERE RN = 1  

像这样尝试

Select * from Dbo.Subject
INNER JOIN (Select DISTINCT ISNULL(MAX(Subjectname,'NoSubject') As Subject FROM TeacherSubject)As Subjectname
ON Subjectname.SubjectID = Subject.SubjectID

最简单的方法是首先让每位教师加入一个科目。所以加入聚合:

select
  t.teacherid, 
  t.teachername, 
  g.gender, 
  t.dob, 
  coalesce(s.subject, 'no subject') as subject, 
  t.contact, 
  t.address, 
  t.email, 
  t.photo
from teacher t
join gender g on g.genderid = t.gender
left join 
(
   select teacherid, max(subjectid) as max_subjectid
   from teachersubject
   group by teacherid
) ts on ts.teacherid = t.teacherid
left join subject s on s.subjectid = ts.max_subjectid;