1435. Create a Session Bar Chart

1435. Create a Session Bar Chart

SQL Schema

Table: Sessions

+---------------------+---------+
| Column Name         | Type    |
+---------------------+---------+
| session_id          | int     |
| duration            | int     |
+---------------------+---------+
session_id is the primary key for this table.
duration is the time in seconds that a user has visited the application.

You want to know how long a user visits your application. You decided to create bins of "[0-5>", "[5-10>", "[10-15>" and "15 minutes or more" and count the number of sessions on it.

Write an SQL query to report the (bin, total) in any order.

The query result format is in the following example.

Sessions table:
+-------------+---------------+
| session_id  | duration      |
+-------------+---------------+
| 1           | 30            |
| 2           | 299           |
| 3           | 340           |
| 4           | 580           |
| 5           | 1000          |
+-------------+---------------+

Result table:
+--------------+--------------+
| bin          | total        |
+--------------+--------------+
| [0-5>        | 3            |
| [5-10>       | 1            |
| [10-15>      | 0            |
| 15 or more   | 1            |
+--------------+--------------+

For session_id 1, 2 and 3 have a duration greater or equal than 0 minutes and less than 5 minutes.
For session_id 4 has a duration greater or equal than 5 minutes and less than 10 minutes.
There are no session with a duration greater or equial than 10 minutes and less than 15 minutes.
For session_id 5 has a duration greater or equal than 15 minutes.

Difficulty:

Easy

Solution:

first table creation and data insertion for non-leetcode premium subscription

create table Sessions (session_id int,duration  int);
INSERT INTO  Sessions VALUES(1,30),(2,299),(3,340),(4,580),(5,1000);
with cte1 as (
SELECT * , case when duration between 0 and 299 then '[0-5>'
             when duration between 300 and 599 then '[5-10>'
             when duration between 600 and 899 then '[10-15>'
             else '15 or more' 
            end as bin from Sessions
),
 cte2 as (select '[0-5>' as bin
 UNION
 SELECT '[5-10>'
 UNION
 SELECT '[10-15>'
 UNION
 SELECT '15 or more'
 )
 SELECT cte2.bin,ifnull(cte.cnt,0) as total FROM  cte2 left join (select bin, count(Session_id) as cnt from cte1 GROUP BY bin) cte on cte.bin= cte2.bin ;

OUTPUT