SQL - 获取列大于特定数量的行

时间:2014-02-07 16:55:32

标签: sql

我需要得到每个lesson_id中第一个得分的总和,但我还需要所有lesson_ids的总得分和最高得分以及其他一些信息:

cdu_groups:
----------------
|id |name      |
----------------
|1  |group_1   |
|2  |group_2   |
----------------

cdu_user_progress145:
-----------------------------------------------------------
|id |uid |group_id |lesson_id |game_id |score |date       |
-----------------------------------------------------------
|1  |145 |1        |1         |0       |40    |1391627323 |
|2  |145 |1        |1         |0       |80    |1391627567 |
|3  |145 |1        |2         |0       |40    |1391627323 |
|4  |145 |1        |3         |0       |30    |1391627323 |
|5  |145 |1        |3         |0       |90    |1391627567 |
|6  |145 |1        |4         |0       |20    |1391627323 |
|7  |145 |1        |5         |0       |35    |1391627323 |
-----------------------------------------------------------

我需要这个输出:

-----------------------------------------------------------------
|name    |group_id |min_score |max_score |... |sum_first_scores |
-----------------------------------------------------------------
|group_1 |1        |20        |90        |... |165              |
-----------------------------------------------------------------

    SELECT 
    cdu_groups.*, 
    MAX(score) AS max_score, 
    MIN(score) AS min_score, 
    COUNT(DISTINCT(lesson_id)) AS scored_lesson_count,
    COUNT(DISTINCT CASE WHEN score >= 75 then lesson_Id ELSE NULL END) as passed_lesson_count, 
    SUM(first_scores.first_score) AS sum_first_scores 
    FROM cdu_user_progress 
    JOIN cdu_groups ON cdu_groups.id = cdu_user_progress.group_id 
    JOIN 
    (
        SELECT lesson_id, MIN(date), score AS first_score FROM cdu_user_progress 
        WHERE cdu_user_progress.uid = 145
        GROUP BY lesson_id          
    ) AS first_scores ON first_scores.lesson_id = cdu_user_progress.lesson_id 
    WHERE cdu_user_progress.uid = 145

我收到了这个错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SUM(first_scores.first_score) AS sum_first_scores FROM cdu_user_progress ' at line 7

0 个答案:

没有答案