简体   繁体   中英

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

I've been working on a school management project. A teacher has multiple subjects, I need to display only one subject in query but I get all the subjects that a teacher has. Now I need only one record for Teacher 2 (TeacherId =2 has two subjects (English & Math) from the above screenshot's query. English or Math any of them will do.

Query in Text:

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

Thanks in advance for helping me a lot.

Take your query add Row_Number() statement as another column and put in the CTE your entire query

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

OR

TRY LIKE THIS

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

The easiest way would be to join just one subject per teacher in the first place. So join with an aggregate:

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;

Make use of distinct clause. This should work for you. In your case place distinct between Select and dbo.Teacher.TeacherId (in the first line).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM