id login_name login_time 1 aa 2002-09-19 2 bb 2002-12-19 3 bb 2002-12-30
如何编写一个SQL语句来查找具有最大登录次数的用户的最新login_time。例如,在此示例数据中,用户“bb”已登录两次,其最新login_time为“2002-12-30”。
答案 0 :(得分:2)
SELECT
id,
MAX(`login_time`) AS `login_time`
FROM table_name
GROUP BY login_name
答案 1 :(得分:2)
这是简单的方法:
SELECT
t.login_name
,COUNT(t.id) AS login_counts
,MAX(t.login_time) AS latest_login_time
FROM this_table AS t
GROUP BY t.login_name
ORDER BY login_counts DESC, login_name
;
第一行为您提供登录次数最多的login_name
。
这是艰难的方式:
SELECT
t.login_name
,MAX(t.login_time) AS latest_login_time
FROM this_table AS t
INNER JOIN (
-- Determine who has the most logins
SELECT TOP 1 x.login_name, COUNT(x.id) AS login_count
FROM this_table AS x
GROUP BY x.login_name
ORDER BY login_count DESC -- to get the highest counts first
) AS m
ON t.login_name = m.login_name
GROUP BY t.login_name
;
这会给你一个名字和日期,就是这样,虽然它没有考虑到最多登录次数可能超过1个名字的可能性。我会把这个留给你弄清楚。
答案 2 :(得分:0)
SELECT login_name, COUNT(*) as num_logins, max(login_time) as last_login_time
FROM table_name ORDER BY num_logins DESC
然后,取决于您使用的sql server,您可以为MS SQL Server添加limit 1
(对于mysql)或top 1
,或者为其他服务器添加其他内容以获取第一个仅记录。
答案 3 :(得分:0)
以下适用于Oracle数据库:
SELECT MAX(LOGIN_TIME)
FROM LOGIN_TABLE
WHERE LOGIN_NAME = (SELECT LOGIN_NAME
FROM (SELECT LOGIN_NAME, COUNT(*) AS LOGIN_COUNT
FROM LOGIN_TABLE
GROUP BY LOGIN_NAME
ORDER BY LOGIN_COUNT DESC)
WHERE ROWNUM = 1)
分享并享受。
答案 4 :(得分:-1)
select *
from [login table]
where login_name [has max] on login_time [is soonest]