如何在mysql中按最小/最大从组中获取最新和最旧的行

时间:2019-05-14 06:01:25

标签: mysql group-by

我有一个应用程序,可以在其中选择当天的第一个和最后一个时间戳记的记录。满足条件的行不止一个,我只需要特定日期的最新行。

SELECT TIMESTAMP, COUNT(DISTINCT employee_id) 
    FROM attendance 
        WHERE Date(TIMESTAMP) BETWEEN STR_TO_DATE('01/04/2019', '%d/%m/%Y') 
                                  AND STR_TO_DATE('30/04/2019', '%d/%m/%Y') 
          AND TIME(TIMESTAMP) < '17:00' 
          AND employee_id=1111 
    GROUP BY DATE(TIMESTAMP);

问题是它不返回那几天的最后/最新记录。

enter image description here

样本数据enter image description here

1 个答案:

答案 0 :(得分:1)

如果您希望在特定日期范围内按天,最旧和最新输入日期,则可以按日期列分组,并按时间戳列排序。

查询获取最新条目:

SELECT TIMESTAMP, COUNT(DISTINCT employee_id) 
   FROM attendance 
        WHERE Date(TIMESTAMP) BETWEEN STR_TO_DATE('01/04/2019', '%d/%m/%Y') 
          AND STR_TO_DATE('30/04/2019', '%d/%m/%Y') 
          AND TIME(TIMESTAMP) < '17:00' 
          AND employee_id=1111 
        GROUP BY DATE(TIMESTAMP)
        ORDER BY(TIMESTAMP) DESC;

查询获取最早的条目:

SELECT TIMESTAMP, COUNT(DISTINCT employee_id) 
    FROM attendance 
        WHERE Date(TIMESTAMP) BETWEEN STR_TO_DATE('01/04/2019', '%d/%m/%Y') 
                                  AND STR_TO_DATE('30/04/2019', '%d/%m/%Y') 
           AND TIME(TIMESTAMP) < '17:00' 
           AND employee_id=1111 
        GROUP BY DATE(TIMESTAMP)
        ORDER BY(TIMESTAMP) ASC;

请注意,我只使用了GROUP BY语句和ORDER BY DESC / ASC(根据您分别提取与指定条件匹配的最新/最旧数据的要求)。

希望它能起作用!