简体   繁体   中英

Complex SQL query (COUNT, DISTINCT, case when, LEFT OUTER JOIN)

I have two tables

users:

+------------+-----------+
| user_id    | company   |
+------------+-----------+
| 1          | Apple     |
| 2          | Microsoft |
+------------+-----------+

sessions:

+------------+---------+------------+-----------+------------+
| session_id | user_id | start_time | end_time  | user_agent |
+------------+---------+------------+-----------+------------+
| 1          | 1       | 12:00:00   | 12:20:00  | X          |
| 2          | 1       | 14:10:00   | 14:14:00  | Y          |
+------------+---------+------------+-----------+------------+

I want to query both tables in one query and have an output that looks like this:

+------------+-----------+--------------------+
| user_id    | company   | unique_user_agents |
+------------+-----------+--------------------+
| 1          | Apple     | 2                  |
| 2          | Microsoft | 0                  |
+------------+-----------+--------------------+

with a query like this:

x
SELECT users.user_id, users.company_name, COUNT(DISTINCT (case when sessions.start_time >= '11:00:00' AND sessions.end_time <= '15:30:00' then sessions.user_agent)) FROM users GROUP BY users.user_id LEFT OUTER JOIN sessions ON users.user_id = sessions.user_id

however i'm getting errors about the syntax, i know that it's wrong but i can't rearrange to be successful.

Any ideas?

Case when always ends with an end and the group by has to be kept after all the joins

SELECT users.user_id, users.company_name, COUNT(DISTINCT case when sessions.start_time >= '11:00:00' AND sessions.end_time <= '15:30:00' then sessions.user_agent end) 
FROM users 
LEFT OUTER JOIN sessions 
  ON users.user_id = sessions.user_id
GROUP BY users.user_id 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM