开发者

Format output in SQL so that multiple values of column b are associated with one value of column a

开发者 https://www.devze.com 2023-01-30 10:25 出处:网络
This is my select statement: SELECT lastName + \',\' + firstName as Name, classNumber FROM STUDENT RIGHT JOIN ENROLL ON Enroll.stuid = Student.stuid

This is my select statement:

SELECT lastName + ',' + firstName as Name,  
       classNumber
FROM STUDENT 
RIGHT JOIN ENROLL ON Enroll.stuid = Student.stuid

and the output:

name           classnumber
--------------------------
Smith,Tom      ART103A  
Smith,Tom      HST205A  
Chin,Ann       ART103A  
Chin,Ann       CSC201A  
Chin,Ann       MTH103A  
McCarthy,Owen  ART103A   
McCarthy,Owen  MTH103C  
Rivera,Jane    CSC201A 开发者_如何学Python 
Rivera,Jane    MTH101B  

I would like it so that each name only appears in the first column once. Any help or idea greatly appreciated.


As the rows are all independent from each other, no row can know if it's the first one.

What you could do is to GROUP BY Name and put all the classNumbers together in a list like this:

SELECT lastName + ',' + firstName AS Name,
       GROUP_CONCAT(classNumber SEPARATOR '\n') AS classNumbers
FROM student
RIGHT JOIN Enroll ON (Student.stuid = Enroll.stuid)
GROUP BY Name


if only one class will appear.

SELECT lastName + ',' + firstName as Name, classNumber
FROM STUDENT 
RIGHT JOIN 
(select Student.stuid as stuid, min(classNumber) as ClassNumber 
 from ENROLL Enroll inner Join Student
 ON (Student.stuid = Enroll.stuid) group by Student.stuid) AS NewEnrol 
 ON NewEnroll.stuid = Student.stuid

Or

SELECT lastName + ',' + firstName as Name,Min(classNumber)
FROM STUDENT 
RIGHT JOIN ENROLL ON Enroll.stuid = Student.stuid
Group By lastname+','+firstname
0

精彩评论

暂无评论...
验证码 换一张
取 消