将MIN()函数与INNER JOIN一起使用

时间:2018-12-30 01:36:43

标签: mysql sql inner-join min

我有一个问题。我正在Coursera上进行数据科学SQL课程,并具有以下任务:

  

问题7:使用INNER JOIN查找困难程度为96的社区区域的最低“平均学生出勤率”。

我解决了这样的问题:

SELECT S.AVERAGE_STUDENT_ATTENDANCE, S.COMMUNITY_AREA_NAME, C.HARDSHIP_INDEX
FROM CHICAGO_PUBLIC_SCHOOLS as S
INNER JOIN CENSUS_DATA as C
ON C.COMMUNITY_AREA_NUMBER = S.COMMUNITY_AREA_NUMBER
WHERE C.HARDSHIP_INDEX = 96
ORDER BY S.AVERAGE_STUDENT_ATTENDANCE ASC
LIMIT 1;

但是,最初我想解决的问题是没有ORDER BYLIMIT的情况。 MIN(S.AVERAGE_STUDENT_ATTENDANCE)函数对我不起作用-我收到错误消息:

An expression starting with "HARDSHIP_INDEX" specified in a SELECT clause, HAVING clause, or ORDER BY clause is not specified in the GROUP BY clause or it is in a SELECT clause, HAVING clause, or ORDER BY clause with a column function and no GROUP BY clause is specified.. SQLCODE=-119, SQLSTATE=42803, DRIVER=4.24.92

是否可以通过MIN解决问题?

非常感谢您。

2 个答案:

答案 0 :(得分:0)

使用min的方法如下:

SELECT
    S.AVERAGE_STUDENT_ATTENDANCE
  , S.COMMUNITY_AREA_NAME
  , C.HARDSHIP_INDEX
FROM CHICAGO_PUBLIC_SCHOOLS AS S
INNER JOIN CENSUS_DATA AS C ON C.COMMUNITY_AREA_NUMBER = S.COMMUNITY_AREA_NUMBER
WHERE C.HARDSHIP_INDEX = 96
AND S.AVERAGE_STUDENT_ATTENDANCE = (
    SELECT
        MIN( S.AVERAGE_STUDENT_ATTENDANCE )
    FROM CHICAGO_PUBLIC_SCHOOLS AS S
    INNER JOIN CENSUS_DATA AS C ON C.COMMUNITY_AREA_NUMBER = S.COMMUNITY_AREA_NUMBER
    WHERE C.HARDSHIP_INDEX = 96
)

根据所使用的数据库,如果它支持公用表表达式,则可以执行以下操作:

WITH cte
AS (
    SELECT
        S.AVERAGE_STUDENT_ATTENDANCE
      , S.COMMUNITY_AREA_NAME
      , C.HARDSHIP_INDEX
    FROM CHICAGO_PUBLIC_SCHOOLS AS S
    INNER JOIN CENSUS_DATA AS C ON C.COMMUNITY_AREA_NUMBER = S.COMMUNITY_AREA_NUMBER
    WHERE C.HARDSHIP_INDEX = 96
)
SELECT
    *
FROM cte
WHERE AVERAGE_STUDENT_ATTENDANCE = (
    SELECT
        MIN( AVERAGE_STUDENT_ATTENDANCE )
    FROM cte
)

如果您的MySQL版本支持窗口功能(v8或更高版本),则类似的方法也可能起作用:

SELECT
    AVERAGE_STUDENT_ATTENDANCE
  , COMMUNITY_AREA_NAME
  , HARDSHIP_INDEX
FROM (
    SELECT
        S.AVERAGE_STUDENT_ATTENDANCE
      , S.COMMUNITY_AREA_NAME
      , C.HARDSHIP_INDEX
      , MIN( S.AVERAGE_STUDENT_ATTENDANCE ) OVER () AS min_att
    FROM CHICAGO_PUBLIC_SCHOOLS AS S
    INNER JOIN CENSUS_DATA AS C ON C.COMMUNITY_AREA_NUMBER = S.COMMUNITY_AREA_NUMBER
    WHERE C.HARDSHIP_INDEX = 96
) sq
WHERE AVERAGE_STUDENT_ATTENDANCE = min_att

请注意OVER(),即,在所有数据库中都不允许over子句中的任何内容,它可能需要类似over(partition by C.HARDSHIP_INDEX)的内容。

答案 1 :(得分:0)

您的方法是正确的使用方法。但是,如果您确实想要执行以下操作,则可以使用group_concat() / substring_index()技巧:

SELECT MAX(S.AVERAGE_STUDENT_ATTENDANCE),
       SUBSTRING_INDEX(GROUP_CONCAT(S.COMMUNITY_AREA_NAME ORDER BY S.AVERAGE_STUDENT_ATTENDANCE ASC), ',', 1),
       SUBSTRING_INDEX(GROUP_CONCAT(C.HARDSHIP_INDEX ORDER BY S.AVERAGE_STUDENT_ATTENDANCE ASC), ',', 1)
FROM CHICAGO_PUBLIC_SCHOOLS S INNER JOIN
     CENSUS_DATA  C
     ON C.COMMUNITY_AREA_NUMBER = S.COMMUNITY_AREA_NUMBER
WHERE C.HARDSHIP_INDEX = 96;