Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL SELECT MAX of SUM() values

Tags:

sql

mysql

max

sum

I have this MySQL query:

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

This outputs:

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

I want to select only the row with highest total_days, in my example 129.

How can I do this?

like image 537
David Avatar asked Nov 17 '25 12:11

David


1 Answers

this will show duplicate records having highest total_days, eg

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

query

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
    )
like image 178
John Woo Avatar answered Nov 20 '25 07:11

John Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!