显示每天的第一个和最后一个日志

vlju58qv  于 2021-06-18  发布在  Mysql
关注(0)|答案(5)|浏览(285)

我有一个带有列的mysql表:id(primary)、name(varchar)、time(timestamp)

ID , NAME , TIME

我只想得到每天的第一个和最后一个日志

example if i have data like this 

1,name,2018-20-21 12:35:00
2,name,2018-20-21 13:38:00
3,name,2018-20-21 14:25:00
4,name,2018-20-21 15:39:00
5,name,2018-20-21 21:48:00 
6,name,2018-20-22 13:25:00
7,name,2018-20-22 14:39:00
8,name,2018-20-22 19:48:00

我想就这样进去

1,name,2018-20-21 12:35:00
 5,name,2018-20-21 21:48:00 

 6,name,2018-20-22 13:25:00
 8,name,2018-20-22 19:48:00
yfwxisqw

yfwxisqw1#

希望这有帮助。

SELECT id, tmp.name, tmp.time FROM
(SELECT id, name, min(time) as time FROM table1 GROUP BY DATE(time)
UNION ALL
(SELECT id, name, max(time) as time FROM table1 GROUP BY DATE(time)) tmp
ORDER BY tmp.time
rqqzpn5f

rqqzpn5f2#

您可以尝试为每一天选择最小值和最大值,因为您需要整行,所以需要一个连接,并且要过滤掉实际的最小值和最大值,需要一个aub查询

SELECT id, name, time
FROM
(

SELECT t2.*, MIN(DATE(t.time)) As min0 MAX(DATE(t.time)) As max0
FROM
 table t
 INNER JOIN table t2 ON t.id = t2.id
GROUP BY
 DATE (t.time), 
min0, 
max0
) a
omvjsjqw

omvjsjqw3#

您可以按日期使用最小和最大时间组的并集,并将其与表连接起来

select * from my_table 
    inner join  (     
    select * from (
     select   min(time) my_time 
     from my_table  
     group by date(time)
     union 
     select   max(time)
     from my_table  
     group by date(time)
    ) t on t.my_time = my_table.time
    order by  my_table.time
vaqhlq81

vaqhlq814#

SELECT 
    l.id,l.name,l.time
FROM
    log l
        LEFT JOIN
    (SELECT 
        max(time) as maxTime
    FROM
        log
    GROUP BY date(time)) l1 ON l.time = l1.maxTime
        LEFT JOIN
    (SELECT 
        min(time) as minTime
    FROM
        log
    GROUP BY date(time)) l2 ON l.time = l2.minTime
WHERE
    (maxTime IS NOT NULL
        OR minTime IS NOT NUll);
SELECT * from stack.log;
roqulrg3

roqulrg35#

试试这个:
按日期(时间)从表组中选择名称、最大(时间)、最小(时间);

相关问题