SQL select 每一个
MSQL select one of each
我有一个像这样的table...
username action time
user1 login 00.00.00
user1 logout 01.00.00
user2 login 02.00.00
我想 select 每个用户名在 02.00.00 的最后一个操作所以它必须是这样的..
user1 logout
user2 login
我已经试过了,但看起来还没有完成。
select (distinct username), action from log where date(time) <= '02.00.00'
提前谢谢你。
您可以在子查询中找到每个用户的最大时间并将其与主 table 内部连接,如下所示:
select a.*
from log a
inner join (
select username, max(time) time
from log
where time <= '02.00.00'
group by username
) b on a.username = b.username
and a.time = b.time;
这里需要注意的一点是,如果有多行具有相同的最大时间,查询将显示所有这些。
使用子查询
select username,action from log where time in( select max(time) from log group by username);
使用时间段:
select username,action from log where time in( select max(time) from log group by username having time < '2.00.00');
试试这个
select * from (select * from log order by time desc) log group by username;
我有一个像这样的table...
username action time
user1 login 00.00.00
user1 logout 01.00.00
user2 login 02.00.00
我想 select 每个用户名在 02.00.00 的最后一个操作所以它必须是这样的..
user1 logout
user2 login
我已经试过了,但看起来还没有完成。
select (distinct username), action from log where date(time) <= '02.00.00'
提前谢谢你。
您可以在子查询中找到每个用户的最大时间并将其与主 table 内部连接,如下所示:
select a.*
from log a
inner join (
select username, max(time) time
from log
where time <= '02.00.00'
group by username
) b on a.username = b.username
and a.time = b.time;
这里需要注意的一点是,如果有多行具有相同的最大时间,查询将显示所有这些。
使用子查询
select username,action from log where time in( select max(time) from log group by username);
使用时间段:
select username,action from log where time in( select max(time) from log group by username having time < '2.00.00');
试试这个
select * from (select * from log order by time desc) log group by username;