简体   繁体   English

编写查询以查找登录用户

[英]Write a query to find logged user

I have a table "record" with the columns:我有一个包含列的“记录”表:

userId

ip

timestamp

userAgent

How do I write query that will list the userId and month for any occasions where a user logged in more than 10 times in a month?如果用户在一个月内登录超过 10 次,我该如何编写查询来列出 userId 和月份?

Assuming your record table as an entry per login.假设您的记录表是每次登录的条目。 The query is relatively straight forward (here using PostgresSQL specific function for the month extraction):查询相对简单(此处使用 PostgresSQL 特定的 function 提取月份):

select userId, date_trunc('month', timestamp) 'Month', count(*)
group by 1, 2
having count(*) > 10;
  • MySQL would use extract('YEAR_MONTH' from timestamp) MySQL 将使用extract('YEAR_MONTH' from timestamp)
  • PostgreSQL uses date_trunc('month', timestamp) to extract a year/month PostgreSQL 使用date_trunc('month', timestamp)提取年/月
  • SQLite3 would use strftime('%Y-%m', timestamp) SQLite3 将使用strftime('%Y-%m', timestamp)

With MySQL you can leave out the count(*) from the select expression, others you hide it with a sub-query:使用 MySQL,您可以从 select 表达式中省略 count(*),其他的您可以使用子查询隐藏它:

select userId, Month from (
   ...
 ) as t;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM