我有这个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 |
+------------+---------------+
我想在我的示例129中仅选择total_days
最高的行。
我该怎么做?
答案 0 :(得分:4)
这将显示具有最高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
)
答案 1 :(得分:1)
尝试添加ORDER BY total_days DESC LIMIT 0,1
这将按大多数排序,并且只返回最佳答案。
答案 2 :(得分: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