MySQL SUM with CASE按日期选择最新记录

时间:2017-01-05 19:47:15

标签: mysql

我已经使SUM CASE语句正常工作了。问题是我有多个具有相似标准的记录,所以我想按日期选择最新记录。

 SELECT 
    SUM(CASE WHEN planning like 'Rotation%' THEN 1 ELSE 0 END + 
        CASE WHEN assessmentanddata like 'Collects%' THEN 1 else 0 END +
        CASE WHEN path like 'Same%' THEN 1 else 0 END +
        CASE WHEN place like 'Move%' THEN 1 else 0 END +
        CASE WHEN pace like 'Timer%' THEN 1 else 0 END +
        CASE WHEN classroommanagement like 'Restating%' THEN 1 else 0 END +
        CASE WHEN teacherrole like 'Mini%' THEN 1 else 0 END +
        CASE WHEN studentengagement like 'Follow%' THEN 1 else 0 END +
        CASE WHEN studentcollaboration like 'Collects%' THEN 1 else 0 END +
        CASE WHEN technology like 'Technology%' THEN 1 else 0 END)  AS p1
    from ruberic where schoolId = 1 

表中的示例将是DATE,SCHOOLID和TEACHERID的这3列:

  

2016-12-05 1 1 - >这条记录没问题

     

2016-12-05 1 4 - >与下面的记录比较时,仅选择此项

     

2016-12-05 1 4

1 个答案:

答案 0 :(得分:0)

以我所看到的为基础(我没有看到日期的字段名称,因此假设日期)

这使用corrects子查询和exists语句来标识每个teacherID和school的max(日期),然后通过着色限制主要数据集。

SELECT 
    SUM(CASE WHEN planning like 'Rotation%' THEN 1 ELSE 0 END + 
        CASE WHEN assessmentanddata like 'Collects%' THEN 1 else 0 END +
        CASE WHEN path like 'Same%' THEN 1 else 0 END +
        CASE WHEN place like 'Move%' THEN 1 else 0 END +
        CASE WHEN pace like 'Timer%' THEN 1 else 0 END +
        CASE WHEN classroommanagement like 'Restating%' THEN 1 else 0 END +
        CASE WHEN teacherrole like 'Mini%' THEN 1 else 0 END +
        CASE WHEN studentengagement like 'Follow%' THEN 1 else 0 END +
        CASE WHEN studentcollaboration like 'Collects%' THEN 1 else 0 END +
        CASE WHEN technology like 'Technology%' THEN 1 else 0 END)  AS p1
FROM
    ruberic R1
WHERE
    schoolId = 1 
    AND EXISTS (SELECT Null 
                FROM ruberic r2
                WHERE R2.SchoolID = R1.SchoolID
                  AND R2.TeacherID = R1.TeacherID
                GROUP BY SchoolID, TeacherID
                HAVING R1.Date = MAX(R2.Date) )