0

my goal is detect all usernames and count each username login time in 24 hours. I was rite code separately but i cant combine it.

SELECT
   DISTINCT "username"
FROM
   my_table;

my second query is get me count log related this username

select count(*) 
from my_table as "foo" where "username" = 'example_username' and  "foo"."timestamp" BETWEEN NOW() - INTERVAL '24 HOURS' AND NOW()

ı want to write one query this query detect unique/distinct usernames and return me last 24 hours logs for each username

if we think this query return a variable list

SELECT
   DISTINCT "username"           
FROM
   my_table;

variable_list =(username1,username2,...)

run that query for each username in variable_list

select count(*) 
from my_table as "foo" where "username" = 'example_username' and  "foo"."timestamp" BETWEEN NOW() - INTERVAL '24 HOURS' AND NOW()

how can ı do that ? and what is the right way for solve this problem ?

Mehmet Başaran
  • 77
  • 2
  • 10

2 Answers2

0

I think you just want a WHERE clause. Assuming that you have no future timestamps:

SELECT DISTINCT username         
FROM my_table
WHERE timestamp >= NOW() - INTERVAL '24 HOURS' ;

If you want to count users in the last 24 hours, use aggregation:

SELECT username, COUNT(*) FILTER (WHERE timestamp >= NOW() - INTERVAL '24 HOURS')     
FROM my_table
GROUP BY username;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Use CTE to make a list of users and then just use a left join with aggregation.

WITH user_list as (SELECT
   DISTINCT "username"
   FROM
   my_table)
SELECT 
  user_list."username"
  ,count(*) 
FROM user_list 
LEFT JOIN my_table as "foo" 
   ON "foo"."username"=user_list."username"
WHERE  "foo"."timestamp" BETWEEN NOW() - INTERVAL '24 HOURS' AND NOW()
GROUP BY user_list."username"
Gabriel Durac
  • 2,610
  • 1
  • 12
  • 13