数据科学家 算法工程师 面试准备 全套-github.com/LongxingTan/Machine-learning-interview
1050. 合作过至少三次的演员和导演
sql
SELECT actor_id, director_id
FROM ActorDirector
GROUP BY actor_id, director_id
HAVING COUNT(*) >= 3;
1076. Project Employees II
sql
SELECT TOP 1 WITH TIES project_id
FROM Project
GROUP BY project_id
ORDER BY COUNT(employee_id) DESC;
1082. Sales Analysis I
sql
SELECT TOP 1 WITH TIES seller_id
FROM Sales
GROUP BY seller_id
ORDER BY SUM(price) DESC;
1141. 查询近30天活跃用户数
sql
SELECT activity_date as day, COUNT(DISTINCT user_id) as active_users
FROM Activity
WHERE activity_date between '2019-06-28' and '2019-07-27'
GROUP BY activity_date;
1148. 文章浏览 I
sql
SELECT DISTINCT author_id as id
FROM Views
WHERE author_id = viewer_id
ORDER BY id;
1149. Article Views II
sql
SELECT DISTINCT viewer_id as id
FROM Views
GROUP BY viewer_id, view_date
HAVING COUNT(DISTINCT article_id) > 1
ORDER BY id;
182. 查找重复的电子邮箱
聚合函数(如 COUNT)通常需要与 GROUP BY 子句一起使用,并且过滤条件应该放在 HAVING 子句中。直接在 WHERE 子句中使用聚合函数会导致语法错误
sql
SELECT email as email
FROM Person
GROUP BY email
HAVING COUNT(email) > 1;
511. 游戏玩法分析 I
处理聚合查询时,MIN 是一个更通用的解决方案,适用于所有 SQL 数据库。TOP 1 则更适合用于非聚合查询中选择排序后的第一行记录
sql
SELECT player_id, MIN(event_date) as first_login
FROM Activity
GROUP BY player_id;
578. Get Highest Answer Rate Question
sql
SELECT TOP 1 question_id as survey_log
FROM survey_log
GROUP BY question_id
ORDER BY COUNT(answer_id) * 1.0 / (COUNT(*) - COUNT(answer_id)) DESC;
584. 寻找用户推荐人
sql
SELECT name
FROM Customer
WHERE referee_id != 2 OR referee_id IS NULL;
586. 订单最多的客户
sql
SELECT customer_number
FROM orders
GROUP BY customer_number
ORDER BY COUNT(*) DESC
LIMIT 1;
595. 大的国家
sql
SELECT name, population, area
FROM World
WHERE area >= 3000000 OR population >= 25000000;
596. 超过5名学生的课
sql
SELECT class
FROM Courses
GROUP BY class
HAVING COUNT(*) >= 5;
619. 只出现一次的最大数字
多一层为了空表格时输出null
sql
SELECT (
SELECT num
FROM MyNumbers
GROUP BY num
HAVING COUNT(*) = 1
ORDER BY num DESC
LIMIT 1
) as num;
620. 有趣的电影
sql
SELECT *
FROM cinema
WHERE description != 'boring' AND id % 2 = 1
ORDER BY rating DESC;