I have an Azure SQL Database with a table Logins in this format:
UserId | LoginDate |
---|---|
ABC123 | 2020-07-10 19:41:51.1256874 |
ABC123 | 2020-07-11 15:52:43.5685147 |
XYZ789 | 2020-06-12 18:23:15.5524874 |
I need to write a query that will get the number of users that logged in every day in a month. I'm not really a SQL guy, so my first thought was to loop through the user ids and the dates in a date range and increment a counter, but I soon figured out that loops don't perform well in SQL. I have read some articles and posts about SQL being set-based, but I haven't figured out how to apply what I read to my problem. Any help would be appreciated!
You would convert the login date column to a date and aggregation:
select convert(date, logindate), count(distinct userid)
from t
group by convert(date, logindate);
Note that this uses count(distinct)
. If a user logins in multiple times on the same day, the user only counts once.
You can add a where
clause for a particular month. Something like this:
where logindate >= '2021-01-01' and logindate < '2021-02-01'
for January 2021.
EDIT:
If you want the number of users who logged in every day during a specific period, then:
select count(*)
from (select userid, convert(date, logindate) as the_date,
count(*) over (partition by userid) as num_dates
from t
where logindate >= @start and
logindate < dateadd(day, 1, @end)
group by userid, convert(date, logindate)
) u
where num_dates = datediff(day, @end, @start) + 1;
Or:
select count(*)
from (select userid,
count(distinct convert(date, logindate)) num_dates
from t
where logindate >= @start and
logindate < dateadd(day, 1, @end)
group by userid
) u
where num_dates = datediff(day, @end, @start) + 1;
You can group by user, filter the query for the month that you want and set the condition in the HAVING
clause:
SElECT UserId
FROM Logins
WHERE CONVERT(date, LoginDate) BETWEEN '2021-01-01' AND '2021-01-31' -- for Jan 2021
-- or with YEAR() and MONTH()
-- WHERE YEAR(LoginDate) = 2021 AND MONTH(LoginDate) = 1
GROUP BY UserId
HAVING COUNT(DISTINCT CONVERT(date, LoginDate)) = DAY(EOMONTH(MIN(LoginDate)))
If you want only the number of users use COUNT()
window function:
SElECT DISTINCT COUNT(*) OVER () counter
FROM Logins
WHERE CONVERT(date, LoginDate) BETWEEN '2021-01-01' AND '2021-01-31' -- for Jan 2021
-- or with YEAR() and MONTH()
-- WHERE YEAR(LoginDate) = 2021 AND MONTH(LoginDate) = 1
GROUP BY UserId
HAVING COUNT(DISTINCT CONVERT(date, LoginDate)) = DAY(EOMONTH(MIN(LoginDate)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.