SQL:每种类型都需要SUM列

时间:2014-02-07 19:25:17

标签: sql

如何在每节课的最短日期找到所有分数的总和_请:

-----------------------------------------------------------
|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    |1391628000 |
|7  |145 |1        |5         |0       |35    |1391628000 |
-----------------------------------------------------------

我需要输出:

-------------------
|sum_first_scores |
-------------------
|165              |
-------------------

到目前为止我有这个,它列出了每节课每个最小日期的分数,但我需要将这些结果总结如上:

SELECT lesson_id, MIN(date), score AS first_score FROM cdu_user_progress 
WHERE cdu_user_progress.uid = 145
GROUP BY lesson_id

1 个答案:

答案 0 :(得分:0)

您可以将第一个分数标识为不存在先前记录的分数。然后拿下总和:

select sum(score)
from edu_user_progress eup
where cdu_user_progress.uid = 145 and
      not exists (select 1
                  from edu_user_progress eup2
                  where eup2.uid = eup.uid and
                        eup2.lesson_id = eup.lesson_id and
                        eup2.date < eup.date
                 );

这假设课程ID的最小日期只有一个分数。