Skip to content
Advertisement

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?

Advertisement

Answer

Assuming your record table as an entry per login. The query is relatively straight forward (here using PostgresSQL specific function for the month extraction):

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

With MySQL you can leave out the count(*) from the select expression, others you hide it with a sub-query:

select userId, Month from (
   ...
 ) as t;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement