将聚合字符串函数与子查询一起使用

时间:2019-06-03 09:05:07

标签: mysql sql string subquery aggregate

此查询选择以下内容:

SELECT jobs.JobID, school.School_Name, 
       CONCAT(staff.First_Name, ' ', staff.Last_Name) AS 'Full_Name', 
       staff.Phone_Number, role.Role
  FROM jobs
 INNER JOIN school ON jobs.SchoolID=school.SchoolID
 INNER JOIN staff ON jobs.StaffID=staff.staffID
 INNER JOIN role ON jobs.roleID=role.roleID
 ORDER BY staff.StaffID asc


JOB ID  FULL NAME   ROLE
------  ---------   ----------
1       BOB         PRINCIPLE
2       BOB         TEACHER
3       JACK        TEACHER
4       SARAH       ACCOUNTANT
5       SARAH       NURSE

ROLE ID    ROLE
------    ----------
1         TEACHER
2         PRINCIPLE
4         ACCOUNTANT
5         NURSE

但是,我希望结果只采用RoleID最大的角色:

BOB     PRINCIPLE
JACK    TEACHER
SARAH   NURSE

我知道我可以通过以下方式将其分组连接,但是之后该怎么办?

SELECT Full_Name, GROUP_CONCAT(Role) AS Role
  FROM
 (
  SELECT jobs.JobID, school.School_Name, CONCAT(staff.First_Name, ' ', staff.Last_Name) 
     AS Full_Name, staff.Phone_Number, role.Role
    FROM jobs
   INNER JOIN school ON jobs.SchoolID=school.SchoolID
   INNER JOIN staff ON jobs.StaffID=staff.staffID
   INNER JOIN role ON jobs.roleID=role.roleID
   ORDER BY staff.StaffID asc
 ) q
GROUP BY Full_Name

据我了解,我将需要一个子查询来过滤字符串?任何帮助表示赞赏,谢谢。

2 个答案:

答案 0 :(得分:1)

使用相关子查询

dist/

或使用rownumber()(如果它是mysql 8.0或以上版本)

 select a.* from (
    SELECT jobs.JobID, school.School_Name, 
           CONCAT(staff.First_Name, ' ', staff.Last_Name) AS 'Full_Name', 
           staff.Phone_Number, role.Role,staff.staffID,role.roleID
      FROM jobs
     INNER JOIN school ON jobs.SchoolID=school.SchoolID
     INNER JOIN staff ON jobs.StaffID=staff.staffID
     INNER JOIN role ON jobs.roleID=role.roleID
   ) a
 where (a.staffID,a.roleID) in (
      SELECT staff.staffID,MAX(Jobs.roleid) roleID
FROM Staff INNER JOIN Jobs  ON jobs.StaffID=staff.staffID
GROUP BY staff.staffID)

答案 1 :(得分:1)

您也可以选中此选项-

SELECT
jobs.JobID, 
school.School_Name, 
CONCAT(staff.First_Name, ' ', staff.Last_Name) AS 'Full_Name', 
staff.Phone_Number, 
role.Role
FROM staff
INNER JOIN jobs ON jobs.StaffID=staff.staffID
INNER JOIN school ON jobs.SchoolID=school.SchoolID
INNER JOIN role ON jobs.roleID=role.roleID
INNER JOIN (
    SELECT staff.staffID,MAX(Jobs.roleid) roleid
    FROM Staff INNER JOIN Jobs  ON jobs.StaffID=staff.staffID
    GROUP BY staff.staffID
 ) A ON jobs.StaffID = A.StaffID AND Jobs.roleID = A.roleid