3

我有这个 MySQL 查询:

SELECT 
    SUM(scpe.scpe_estemated_days) AS total_days,
    scp.cpl_startdate
FROM
    studentcourseplanelements scpe
        INNER JOIN
    studentcourseplan scp ON scp.cpl_id = scpe.scpe_cpl_id
        INNER JOIN
    (SELECT 
        sd1.student_id, sd1.student_startdate
    FROM
        studentdates sd1
    WHERE
        sd1.student_id = '360'
    LIMIT 1) sd ON sd.student_id = scp.student_id
GROUP BY scp.cpl_id

这输出:

+------------+---------------+
| total_days | cpl_startdate |
+------------+---------------+
|          5 | 2012-11-01    |
|        129 | 2012-11-02    |
+------------+---------------+

我只想选择最高的行total_days,在我的示例中为 129。

我怎样才能做到这一点?

4

3 回答 3

5

这将显示重复记录最高total_days,例如

+------------+---------------+
| total_days | cpl_startdate |
+------------+---------------+
|          5 | 2012-11-01    |
|        129 | 2012-11-02    |  <= shown
|        129 | 2012-11-03    |  <= shown
+------------+---------------+

询问

SELECT  SUM(scpe.scpe_estemated_days) AS total_days,
        scp.cpl_startdate
FROM    studentcourseplanelements scpe INNER JOIN studentcourseplan scp
            ON scp.cpl_id = scpe.scpe_cpl_id
        INNER JOIN
        (SELECT  sd1.student_id, sd1.student_startdate
         FROM    studentdates sd1
         WHERE   sd1.student_id = '360'
         LIMIT 1) sd ON sd.student_id = scp.student_id
GROUP BY scp.cpl_id
HAVING SUM(scpe.scpe_estemated_days) = 
    (
        SELECT MAX(total_days)
        FROM
        (
            SELECT  SUM(scpe.scpe_estemated_days) AS total_days,
            FROM    studentcourseplanelements scpe INNER JOIN studentcourseplan scp 
                         ON scp.cpl_id = scpe.scpe_cpl_id
                    INNER JOIN
                    (SELECT  sd1.student_id, sd1.student_startdate
                     FROM    studentdates sd1
                     WHERE   sd1.student_id = '360'
                     LIMIT 1) sd ON sd.student_id = scp.student_id
            GROUP BY scp.cpl_id
        ) s
    )
于 2012-11-26T01:32:53.380 回答
1

尝试添加ORDER BY total_days DESC LIMIT 0,1

这将按大多数排序,并且只返回最佳答案。

于 2012-11-26T01:32:32.273 回答
1

基本上,您希望按 SUM 列降序对其进行排序,然后获取列出的第一条记录。试试这个:

SELECT 
    SUM(scpe.scpe_estemated_days) AS total_days,
    scp.cpl_startdate
FROM
    studentcourseplanelements scpe
        INNER JOIN
    studentcourseplan scp ON scp.cpl_id = scpe.scpe_cpl_id
        INNER JOIN
    (SELECT 
        sd1.student_id, sd1.student_startdate
    FROM
        studentdates sd1
    WHERE
        sd1.student_id = '360'
    LIMIT 1) sd ON sd.student_id = scp.student_id
ORDER BY SUM(scpe.scpe_estemated_days) DESC
GROUP BY scp.cpl_id
LIMIT 1 
于 2012-11-26T01:32:46.613 回答