我有一个简单的表“登录”,有两列:
这很简单,只需记录有人登录我的网络应用程序时的用户名和日期时间。但是,有时人们会在一分钟内登录几次...我想尝试运行查询来过滤这些结果,并且只有在同一分钟内有多个登录时才返回一行。
以下是一个例子:
(我通过简单的选择获得结果)
username logged
-------------------
kh0013 2010-08-16 21:29:21.020
tmt0006 2010-08-16 21:24:16.030
jrc0014 2010-08-16 21:17:37.187
jrc0014 2010-08-16 21:17:15.043
jrc0014 2010-08-16 21:17:00.593
jrm0017 2010-08-16 20:52:57.673
as0044 2010-08-16 20:45:51.210
snb0006 2010-08-16 20:33:29.873
weo0021 2010-08-16 19:54:57.093
如您所见,用户“jrc0014”在同一分钟内多次登录。如何编写查询以便用户只记录一次,如下所示:
(期望的结果)
username logged
------------------
kh0013 2010-08-16 21:29:21.020
tmt0006 2010-08-16 21:24:16.030
jrc0014 2010-08-16 21:17:00.593
jrm0017 2010-08-16 20:52:57.673
as0044 2010-08-16 20:45:51.210
snb0006 2010-08-16 20:33:29.873
weo0021 2010-08-16 19:54:57.093
答案 0 :(得分:0)
在SQL Server中,将日期时间设置为分钟,如下所示:
SELECT DISTINCT
username , DATEADD(minute,DATEDIFF(minute,0,logged),0) AS logged
FROM YourTable
答案 1 :(得分:0)
select username, logged
from Logins o
where not exists(select 1
from Logins i
where i.username = o.username
and datediff(second, i.logged, o.logged) <= 60)
)
答案 2 :(得分:0)
要获得列出的输出,请使用:
SELECT yt.username ,
MAX(yt.logged) AS logged
FROM YOUR_TABLE yt
GROUP BY yt.username, DATEADD(minute,DATEDIFF(minute,0,logged),0)