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?
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
)
try adding ORDER BY total_days DESC LIMIT 0,1
This will sort by most, and only return the top answer.
Basically, you want to order it by the SUM column descending, and then get the first record listed. Try this:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.