如何从SQL Server中的INNER JOIN查询中获取DISTINCT行

时间:2015-01-08 11:44:21

标签: sql sql-server sql-server-2008 sql-server-2012

我一直在做一个学校管理项目。一位老师有多个科目,我只需要在查询中显示一个科目,但我得到了老师所有的科目。现在我只需要一个教师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

提前感谢帮助我。

3 个答案:

答案 0 :(得分:2)

将您的查询添加为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  

OR

试试这个

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

答案 1 :(得分:2)

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

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;

答案 2 :(得分:1)

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