I need your help in using case when function. (probably)
I have a data for daily visits to the server. However, I would like to group these user data by their visit frequency. So that I can divide them into groups who visits less than 5 times, 5 to 10 times, and over 10 times. I hear that case when function could help this but I don't have any clue how to run that.
Set out below is the query that I used to derive daily visits, and the following table is the output for the query. If there's anyone who knows how to write that query accordingly, do help me out. Much appreciated.
select aid, count(result_type) as "daily_visits"
FROM [DBO].[TB_SESSION_LOG]
WHERE
log_dt >= @start_date and
log_dt < @end_date
group by svc_cd, aid
order by svc_cd, aid
Try case
and sub query or CTE :
select aid, count(result_type) as "daily_visits",
case
when count(result_type) < 5 then 0
when count(result_type) between 5 and 10 then 1
when count(result_type) > 10 then 2
end as grp
FROM [DBO].[TB_SESSION_LOG]
WHERE
log_dt >= @start_date and
log_dt < @end_date
group by svc_cd, aid
order by svc_cd, aid
Note that I didn't test the above query but it should work or may need small fixes.
You can assign a grouping using CASE
like this:
SELECT aid, COUNT(result_type) as daily_visits,
(CASE WHEN COUNT(result_type) < 5 THEN 'less than 5'
WHEN COUNT(result_type) < 10 THEN 'between 5 and 10'
ELSE '10 or more
END) as grp
FROM [DBO].[TB_SESSION_LOG]
WHERE log_dt >= @start_date and
log_dt < @end_date
GROUP BY aid
I'm not sure if you want additional processing, but this seems to address your question.
Note: This removes svc_cd
from the query. It does not appear to be being used.
It appears you're looking for something like this
with dv_cte(aid, daily_visits) as (
select aid, count(result_type)
from [DBO].[TB_SESSION_LOG]
where log_dt >= @start_date and
log_dt < @end_date
group by svc_cd, aid)
select
case when daily_visits < 5 then '<5'
when daily_visits < 10 then '>5 and <10'
else '10+' end as grp,
count(*) grp_count
from dv_cte
group by
case when daily_visits < 5 then '<5'
when daily_visits < 10 then '>5 and <10'
else '10+' end;
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.