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 に答える