复杂的SQL查询(COUNT,DISTINCT,大小写,LEFT OUTER JOIN)

时间:2018-04-18 17:39:41

标签: mysql sql join count distinct

我有两张桌子

用户:

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

会话:

+------------+---------+------------+-----------+------------+
| 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          |
+------------+---------+------------+-----------+------------+

我想在一个查询中查询两个表,并且输出如下所示:

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

使用如下查询:

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

但是我在语法方面遇到错误,我知道这是错误的,但我无法重新安排成功。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

总是以end结尾并且在所有联接后必须保留group by的情况

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