我有一张下表
ID USER LOG_TIME REASON
1 PK 2018-07-11 11:00:00 R1, R2
2 PK 2018-07-11 10:00:00 R1
3 AK 2018-07-11 11:00:00 R2
4 PK 2018-07-11 11:30:00 R2
5 AK 2018-07-11 10:00:00 R1
6 PK 2018-07-10 10:00:00 R1, R2
7 AK 2018-07-11 09:00:00 R1, R2
8 AK 2018-07-11 07:00:00 R1
9 PK 2018-07-10 11:00:00 R2
10 AK 2018-07-10 11:00:00 R1, R2
我需要具有最后日志时间,最后原因和2018-07-11日志数的详细信息的结果。我使用的查询是
select USER, max(LOG_TIME) as LAST_LOG, max(REASON) as REASON, case when date_format(LOG_TIME,'%Y-%m-%d')='2018-07-11' then count(*) end as CtLog from LogHistory group by USER order by USER;
我得到的结果是错误的。我需要如下结果
USER LAST_LOG REASON CtLog
PK 2018-07-11 11:30:00 R2 3
AK 2018-07-11 11:00:00 R2 4
需要进行哪些更改
您可以在http://sqlfiddle.com/#!9/c97574/3上找到表格并进行查询
答案 0 :(得分:0)
这是一种使用相关子查询获取当天最后一条记录的信息的方法,然后使用另一子查询获取计数:
select lh.*,
(select count(*)
from loghistory lh2
where lh2.user = lh.user and
lh2.log_time >= '2018-07-11' and
lh2.log_time < '2018-07-12'
) as cnt
from loghistory lh
where lh.log_time = (select max(lh2.log_time)
from loghistory lh2
where lh2.user = lh.user
) and
lh.log_time >= '2018-07-11' and
lh.log_time < '2018-07-12';
假设时间是唯一的,您还可以使用聚合子查询和join
进行此操作:
select lh.*, lhmax.cnt
from (select user, count(*) as cnt, max(lh.log_time) as max_log_time
from loghistory lh
where lh.log_time >= '2018-07-11' and
lh.log_time < '2018-07-12'
group by user
) lhmax join
loghistory lh
on lh.user = lhmax.user and lh.log_time = lhmax.max_log_time;