Leetcode SQL 刷题与答案-基础篇

数据科学家 算法工程师 面试准备 全套-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;
相关推荐
工业甲酰苯胺2 小时前
C语言之输入输出
c语言·c++·算法
Minyy112 小时前
牛客网刷题SQL--高级查询
数据库·sql
努力d小白3 小时前
leetcode98.验证二叉搜索树
算法
归寻太乙3 小时前
算法基础Day7(动态规划)
算法·动态规划
hn小菜鸡4 小时前
LeetCode 2320.统计放置房子的方式数
算法·leetcode·职场和发展
高一学习c++会秃头吗4 小时前
leetcode_547 省份数量
算法·leetcode·职场和发展
天赐细莲4 小时前
(仓颉) Cangjie 刷力扣基础语法小结
数据结构·算法·leetcode·职场和发展
dundunmm5 小时前
论文阅读:Statistical Comparisons of Classifiers over Multiple Data Sets
论文阅读·人工智能·算法·机器学习·评估方法
pzx_0015 小时前
【论文阅读】相似误差订正方法在风电短期风速预报中的应用研究
开发语言·论文阅读·python·算法·leetcode·sklearn