# 暴力统计 classSolution: defnumIdenticalPairs(self, nums: List[int]) -> int: ans = 0 for i inrange(len(nums)): for j inrange(i + 1, len(nums)): if nums[i] == nums[j]: ans += 1 return ans
# 模拟 classSolution: defsubtractProductAndSum(self, n: int) -> int: add, mul = 0, 1 while n > 0: add += n % 10 mul *= n % 10 n //= 10 return mul - add
# 暴力 classSolution: defsubtractProductAndSum(self, n: int) -> int: add, mul = 0, 1 for num instr(n): num = int(num) add += num mul *= num return mul - add
# 模拟 classSolution: deftranspose(self, matrix: List[List[int]]) -> List[List[int]]: m, n = len(matrix), len(matrix[0]) transposed = [[0] * m for _ inrange(n)] for i inrange(m): for j inrange(n): transposed[j][i] = matrix[i][j] return transposed
# 模拟 python3_oneline classSolution: deftranspose(self, matrix: List[List[int]]) -> List[List[int]]: returnlist(list(row) for row inzip(*matrix)) # return [list(row) for row in zip(*matrix)] # 强制转换返回列表值
# 枚举每个分割点 classSolution: defmaxScore(self, s: str) -> int: returnmax(s[:i].count('0') + s[i:].count('1') for i inrange(1, len(s)))
# 两次遍历 classSolution: defmaxScore(self, s: str) -> int: ans = score = (s[0] == '0') + s[1:].count('1') for c in s[1:-1]: score += 1if c == '0'else -1 ans = max(ans, score) return ans
Table: Products +-------------+----------+------------+ | product_id | low_fats | recyclable | +-------------+----------+------------+ | 0 | Y | N | | 1 | Y | Y | | 2 | N | Y | | 3 | Y | Y | | 4 | N | N | +-------------+----------+------------+
-- MySQL SELECT product_id FROM products WHERE low_fats ='Y'AND recyclable ='Y' ;
Big Countries - Easy
1 2 3 4 5 6 7 8 9 10 11
Table: World +-------------+---------+ | Column Name | Type | +-------------+---------+ | name | varchar | | continent | varchar | | area | int | | population | int | | gdp | bigint | +-------------+---------+ name is the primary key column
-- MySQL SELECTDISTINCT author_id AS id FROM Views WHERE author_id = viewer_id ORDERBY author_id ;
Invalid Tweets - Easy
1 2 3 4 5 6 7 8
Table: Tweets +----------------+---------+ | Column Name | Type | +----------------+---------+ | tweet_id | int | | content | varchar | +----------------+---------+ tweet_id is the primary key.
查询所有无效推文的编号(ID)。当推文内容中的字符数严格大于 15 时,该推文是无效的。
以任意顺序返回结果表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Input: Tweets table: +----------+----------------------------------+ | tweet_id | content | +----------+----------------------------------+ | 1 | Vote for Biden | | 2 | Let us make America great again! | +----------+----------------------------------+ Output: +----------+ | tweet_id | +----------+ | 2 | +----------+ Explanation: Tweet 1 has length = 14. It is a valid tweet. Tweet 2 has length = 32. It is an invalid tweet.
1 2 3 4 5
-- MySQL SELECT tweet_id FROM tweets WHERECHAR_LENGTH(content) >15 ;
Replace Employee ID With The Unique Identifier - Easy
使用唯一标识码替换员工 ID:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Table: Employees +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | name | varchar | +---------------+---------+ id is the primary key.
Table: EmployeeUNI +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | unique_id | int | +---------------+---------+
展示每位用户的唯一标识码(unique ID );如果某位员工没有唯一标识码,使用 null 填充即可。
Table: Sales +-------------+-------+ | Column Name | Type | +-------------+-------+ | sale_id | int | | product_id | int | | year | int | | quantity | int | | price | int | +-------------+-------+ (sale_id, year) is the primary key of this table. product_id is a foreign key to Product table.
Table: Product +--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | +--------------+---------+ product_id is the primary key of this table.
获取 Sales 表中所有产品对应的产品名称 product_name 以及该产品的所有售卖年份 year 和价格 price。
-- MySQL SELECT p.product_name, s.year, s.price FROM sales s LEFTJOIN product p ON s.product_id = p.product_id ;
Customer Who Visited but Did Not Make Any Transactions - Easy
进店却未进行过交易的顾客:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Table: Visits +-------------+---------+ | Column Name | Type | +-------------+---------+ | visit_id | int | | customer_id | int | +-------------+---------+ visit_id is the primary key for this table.
Table: Transactions +----------------+---------+ | Column Name | Type | +----------------+---------+ | transaction_id | int | | visit_id | int | | amount | int | +----------------+---------+ transaction_id is the primary key for this table.
-- MySQL SELECT customer_id, count(customer_id) count_no_trans FROM visits v LEFTJOIN transactions t ON v.visit_id = t.visit_id WHERE amount ISNULL GROUPBY customer_id ;
Rising Temperature - Easy
1 2 3 4 5 6 7 8 9
Table: Weather +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | recordDate | date | | temperature | int | +---------------+---------+ id is the primary key for this table.
Table: Students +---------------+---------+ | Column Name | Type | +---------------+---------+ | student_id | int | | student_name | varchar | +---------------+---------+ student_id is the primary key.
Table: Subjects +--------------+---------+ | Column Name | Type | +--------------+---------+ | subject_name | varchar | +--------------+---------+ subject_name is the primary key.
Table: Examinations +--------------+---------+ | Column Name | Type | +--------------+---------+ | student_id | int | | subject_name | varchar | +--------------+---------+ 无主键,可能会有重复行。
Input: Students table: +------------+--------------+ | student_id | student_name | +------------+--------------+ | 1 | Alice | | 2 | Bob | | 13 | John | | 6 | Alex | +------------+--------------+ Subjects table: +--------------+ | subject_name | +--------------+ | Math | | Physics | | Programming | +--------------+ Examinations table: +------------+--------------+ | student_id | subject_name | +------------+--------------+ | 1 | Math | | 1 | Physics | | 1 | Programming | | 2 | Programming | | 1 | Physics | | 1 | Math | | 13 | Math | | 13 | Programming | | 13 | Physics | | 2 | Math | | 1 | Math | +------------+--------------+ Output: +------------+--------------+--------------+----------------+ | student_id | student_name | subject_name | attended_exams | +------------+--------------+--------------+----------------+ | 1 | Alice | Math | 3 | | 1 | Alice | Physics | 2 | | 1 | Alice | Programming | 1 | | 2 | Bob | Math | 1 | | 2 | Bob | Physics | 0 | | 2 | Bob | Programming | 1 | | 6 | Alex | Math | 0 | | 6 | Alex | Physics | 0 | | 6 | Alex | Programming | 0 | | 13 | John | Math | 1 | | 13 | John | Physics | 1 | | 13 | John | Programming | 1 | +------------+--------------+--------------+----------------+
1 2 3 4 5 6 7 8 9
-- MySQL SELECT a.student_id, a.student_name, b.subject_name, COUNT(e.subject_name) AS attended_exams FROM Students a CROSSJOIN Subjects b LEFTJOIN Examinations e ON a.student_id = e.student_id AND b.subject_name = e.subject_name GROUPBY a.student_id, b.subject_name ORDERBY a.student_id, b.subject_name
Managers with at Least 5 Direct Reports - Medium
至少有 5 名直接下属的经理:
1 2 3 4 5 6 7 8 9 10
Table: Employee +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | department | varchar | | managerId | int | +-------------+---------+ id is the primary key column.
查询至少有 5 名直接下属的经理。
以 任意顺序 返回结果表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Input: Employee table: +-----+-------+------------+-----------+ | id | name | department | managerId | +-----+-------+------------+-----------+ | 101 | John | A | None | | 102 | Dan | A | 101 | | 103 | James | A | 101 | | 104 | Amy | A | 101 | | 105 | Anne | A | 101 | | 106 | Ron | B | 101 | +-----+-------+------------+-----------+ Output: +------+ | name | +------+ | John | +------+
1 2 3 4 5 6 7 8 9
-- MySQL SELECT name FROM employee AS t1 JOIN( SELECT managerID FROM employee GROUPBY managerID HAVINGCOUNT(managerID) >=5) AS t2 ON t1.id = t2.managerID ;
Confirmation Rate - Medium
确认率:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Table: Signups +----------------+----------+ | Column Name | Type | +----------------+----------+ | user_id | int | | time_stamp | datetime | +----------------+----------+ user_id is the primary key.
Table: Confirmations +----------------+----------+ | Column Name | Type | +----------------+----------+ | user_id | int | | time_stamp | datetime | | action | ENUM | +----------------+----------+ (user_id, time_stamp) is the primary key. user_id is a foreign key.
-- MySQL SELECT s.user_id, IFNULL(ROUND(SUM(action ='confirmed') /COUNT(c.action), 2), 0.00) AS confirmation_rate FROM signups AS s LEFTJOIN confirmations AS c ON s.user_id = c.user_id GROUPBY s.user_id ;
Not Boring Movies - Easy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Input: Cinema table: +----+------------+-------------+--------+ | id | movie | description | rating | +----+------------+-------------+--------+ | 1 | War | great 3D | 8.9 | | 2 | Science | fiction | 8.5 | | 3 | irish | boring | 6.2 | | 4 | Ice song | Fantacy | 8.6 | | 5 | House card | Interesting | 9.1 | +----+------------+-------------+--------+ Output: +----+------------+-------------+--------+ | id | movie | description | rating | +----+------------+-------------+--------+ | 5 | House card | Interesting | 9.1 | | 1 | War | great 3D | 8.9 | +----+------------+-------------+--------+
找出所有影片描述为非 boring 的且 id 为奇数的影片,结果请按等级 rating 排列。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-- MySQL SELECT* FROM cinema WHEREMOD(id, 2) =1 AND description !='boring' ORDERBY rating DESC ;
-- SQL SELECT* FROM cinema WHERE id %2<>0 AND description <>'boring' ORDERBY rating DESC ;
Table: Prices +---------------+---------+ | Column Name | Type | +---------------+---------+ | product_id | int | | start_date | date | | end_date | date | | price | int | +---------------+---------+ (product_id, start_date, end_date) is the primary key.
Table: UnitsSold +---------------+---------+ | Column Name | Type | +---------------+---------+ | product_id | int | | purchase_date | date | | units | int | +---------------+---------+ There is no primary key for this table, it may contain duplicates.
-- MySQL SELECT product_id, Round(SUM(sales) /SUM(units), 2) AS average_price FROM ( SELECT Prices.product_id AS product_id, Prices.price * UnitsSold.units AS sales, UnitsSold.units AS units FROM Prices JOIN UnitsSold ON Prices.product_id = UnitsSold.product_id WHERE UnitsSold.purchase_date BETWEEN Prices.start_date AND Prices.end_date ) T GROUPBY product_id
Project Employees I - Easy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Table: Project +-------------+---------+ | Column Name | Type | +-------------+---------+ | project_id | int | | employee_id | int | +-------------+---------+ (project_id, employee_id) is the primary key of this table. employee_id is a foreign key to Employee table.
Table: Employee +------------------+---------+ | Column Name | Type | +------------------+---------+ | employee_id | int | | name | varchar | | experience_years | int | +------------------+---------+ employee_id is the primary key.
-- MySQL SELECT p.project_id, ROUND(AVG(e.experience_years), 2) AS average_years FROM project p, employee e WHERE p.employee_id = e.employee_id GROUPBY p.project_id ;
Percentage of Users Attended a Contest - Easy
各赛事的用户注册率:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Table: Users
+-------------+---------+ | Column Name | Type | +-------------+---------+ | user_id | int | | user_name | varchar | +-------------+---------+ user_id is the primary key.
Table: Register
+-------------+---------+ | Column Name | Type | +-------------+---------+ | contest_id | int | | user_id | int | +-------------+---------+ (contest_id, user_id) is the primary key.
+-------------+---------+ | Column Name | Type | +-------------+---------+ | query_name | varchar | | result | varchar | | position | int | | rating | int | +-------------+---------+
-- MySQL SELECT query_name, ROUND(AVG(rating/position), 2) quality, ROUND(SUM(IF(rating <3, 1, 0)) *100/COUNT(*), 2) poor_query_percentage FROM Queries GROUPBY query_name
Monthly Transactions I - Medium
每月交易 I:
1 2 3 4 5 6 7 8 9 10 11 12 13
Table: Transactions
+---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | country | varchar | | state | enum | | amount | int | | trans_date | date | +---------------+---------+ id is the primary key The state column is an enum of type ["approved", "declined"].
-- MySQL SELECT DATE_FORMAT(trans_date, '%Y-%m') ASmonth, country, COUNT(*) AS trans_count, COUNT(IF(state ='approved', 1, NULL)) AS approved_count, SUM(amount) AS trans_total_amount, SUM(IF(state ='approved', amount, 0)) AS approved_total_amount FROM transactions GROUPBYmonth, country
Immediate Food Delivery II - Medium
即时食物配送 II:
1 2 3 4 5 6 7 8 9 10 11
Table: Delivery
+-----------------------------+---------+ | Column Name | Type | +-----------------------------+---------+ | delivery_id | int | | customer_id | int | | order_date | date | | customer_pref_delivery_date | date | +-----------------------------+---------+ delivery_id is the primary key
-- MySQL SELECT ROUND(SUM(order_date = customer_pref_delivery_date) *100/COUNT(*), 2) AS immediate_percentage FROM delivery WHERE (customer_id, order_date) IN ( SELECT customer_id, min(order_date) FROM delivery GROUPBY customer_id )
Game Play Analysis IV - Medium
游戏玩法分析 IV:
1 2 3 4 5 6 7 8 9 10 11
Table: Activity
+--------------+---------+ | Column Name | Type | +--------------+---------+ | player_id | int | | device_id | int | | event_date | date | | games_played | int | +--------------+---------+ (player_id, event_date) is the primary key
-- MySQL SELECT ROUND(AVG(a.event_date ISNOTNULL), 2) fraction FROM (SELECT player_id, min(event_date) AS login FROM activity GROUPBY player_id) p LEFTJOIN activity a ON p.player_id = a.player_id AND datediff(a.event_date, p.login) =1
Number of Unique Subjects Taught by Each Teacher - Easy
每位教师所教授的科目种类的数量:
1 2 3 4 5 6 7 8 9 10
Table: Teacher
+-------------+------+ | Column Name | Type | +-------------+------+ | teacher_id | int | | subject_id | int | | dept_id | int | +-------------+------+ (subject_id, dept_id) is the primary key
-- MySQL SELECT teacher_id, COUNT(distinct subject_id) AS cnt FROM teacher GROUPBY teacher_id ;
User Activity for the Past 30 Days I - Easy
查询近 30 天活跃用户数:
1 2 3 4 5 6 7 8 9 10 11
Table: Activity
+---------------+---------+ | Column Name | Type | +---------------+---------+ | user_id | int | | session_id | int | | activity_date | date | | activity_type | enum | +---------------+---------+ There is no primary key for this table, it may have duplicate rows.
-- MySQL SELECT activity_date ASday, COUNT(DISTINCT(user_id)) AS active_users FROM Activity WHERE DATEDIFF('2019-7-27', activity_date) <30AND activity_date <='2019-7-27' GROUPBY activity_date ;
+--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | | unit_price | int | +--------------+---------+ product_id is the primary key
Table: Sales
+-------------+---------+ | Column Name | Type | +-------------+---------+ | seller_id | int | | product_id | int | | buyer_id | int | | sale_date | date | | quantity | int | | price | int | +-------------+---------+ This table has no primary key, it can have repeated rows. product_id is a foreign key to the Product table.
解释: id为1的产品仅在2019年春季销售。 id为2的产品在2019年春季销售,但也在2019年春季之后销售。 id 3的产品在2019年春季之后销售。 我们只退回产品1,因为它是2019年春季才销售的产品。
1 2 3 4 5 6 7 8 9
-- MySQL SELECT sales.product_id AS product_id, product.product_name AS product_name FROM sales LEFTJOIN product ON sales.product_id = product.product_id GROUPBY product_id HAVINGCOUNT(sale_date BETWEEN'2019-01-01'AND'2019-03-31'ORNULL) =COUNT(*)
Classes More Than 5 Students - Easy
超过 5 名学生的课:
1 2 3 4 5 6 7 8 9
Table: Courses
+-------------+---------+ | Column Name | Type | +-------------+---------+ | student | varchar | | class | varchar | +-------------+---------+ (student, class) is the primary key column
Input: Courses table: +---------+----------+ | student | class | +---------+----------+ | A | Math | | B | English | | C | Math | | D | Biology | | E | Math | | F | Computer | | G | Math | | H | Math | | I | Math | +---------+----------+ Output: +---------+ | class | +---------+ | Math | +---------+
-- MySQL -- 方法一:使用 GROUP BY 子句和子查询 SELECT class FROM (SELECT class, COUNT(DISTINCT student) AS num FROM courses GROUPBY class) AS temp_table WHERE num >=5 ;
-- 方法二:使用 GROUP BY 和 HAVING 条件 SELECT class FROM courses GROUPBY class HAVINGCOUNT(DISTINCT student) >=5 ;
Find Followers Count - Easy
求关注者的数量:
1 2 3 4 5 6 7 8 9
Table: Followers
+-------------+------+ | Column Name | Type | +-------------+------+ | user_id | int | | follower_id | int | +-------------+------+ (user_id, follower_id) is the primary key
-- MySQL SELECTMAX(num) AS num FROM(SELECT num FROM mynumbers GROUPBY num HAVINGCOUNT(num) =1) AS t ;
Customers Who Bought All Products - Medium
买下所有产品的客户:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Table: Customer
+-------------+---------+ | Column Name | Type | +-------------+---------+ | customer_id | int | | product_key | int | +-------------+---------+ There is no primary key product_key is a foreign key to Product table.
Table: Product
+-------------+---------+ | Column Name | Type | +-------------+---------+ | product_key | int | +-------------+---------+ product_key is the primary key
-- MySQL SELECT customer_id FROM customer GROUPBY customer_id HAVINGCOUNT(DISTINCT product_key) = ( SELECTCOUNT(DISTINCT product_key) FROM product );
The Number of Employees Which Report to Each Employee - Easy
每位经理的下属员工数量:
1 2 3 4 5 6 7 8 9 10 11
Table: Employees
+-------------+----------+ | Column Name | Type | +-------------+----------+ | employee_id | int | | name | varchar | | reports_to | int | | age | int | +-------------+----------+ employee_id is the primary key
Hercy 有两个需要向他汇报的员工, 他们是 Alice and Bob. 他们的平均年龄是 (41+36)/2 = 38.5, 四舍五入的结果是 39.
1 2 3 4 5 6 7 8 9 10 11 12
-- MySQL SELECT b.employee_id, b.name, COUNT(a.name) reports_count, ROUND(AVG(a.age), 0) average_age FROM Employees AS a JOIN employees AS b ON a.reports_to = b.employee_id GROUPBY b.employee_id ORDERBY b.employee_id ;
Primary Department for Each Employee - Easy
员工的直属部门:
1 2 3 4 5 6 7 8 9 10
Table: Employee
+---------------+---------+ | Column Name | Type | +---------------+---------+ | employee_id | int | | department_id | int | | primary_flag | varchar | +---------------+---------+ (employee_id, department_id) is the primary key
Input: Employee table: +-------------+---------------+--------------+ | employee_id | department_id | primary_flag | +-------------+---------------+--------------+ | 1 | 1 | N | | 2 | 1 | Y | | 2 | 2 | N | | 3 | 3 | N | | 4 | 2 | N | | 4 | 3 | Y | | 4 | 4 | N | +-------------+---------------+--------------+ Output: +-------------+---------------+ | employee_id | department_id | +-------------+---------------+ | 1 | 1 | | 2 | 1 | | 3 | 3 | | 4 | 3 | +-------------+---------------+ Explanation: - The Primary department for employee 1 is 1. - The Primary department for employee 2 is 1. - The Primary department for employee 3 is 3. - The Primary department for employee 4 is 3.
1 2 3 4 5 6 7 8 9 10
-- MySQL SELECT employee_id, department_id FROM employee GROUPBY employee_id HAVINGCOUNT(department_id) =1 UNION SELECT employee_id, department_id FROM employee WHERE primary_flag ='Y' ;
Triangle Judgement - Easy
判断三角形:
1 2 3 4 5 6 7 8 9 10
Table: Triangle
+-------------+------+ | Column Name | Type | +-------------+------+ | x | int | | y | int | | z | int | +-------------+------+ (x, y, z) is the primary key
写一个SQL查询,每三个线段报告它们是否可以形成一个三角形。
以 任意顺序 返回结果表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Input: Triangle table: +----+----+----+ | x | y | z | +----+----+----+ | 13 | 15 | 30 | | 10 | 20 | 15 | +----+----+----+ Output: +----+----+----+----------+ | x | y | z | triangle | +----+----+----+----------+ | 13 | 15 | 30 | No | | 10 | 20 | 15 | Yes | +----+----+----+----------+
1 2 3 4 5 6 7 8 9 10 11
-- MySQL SELECT x, y, z, CASE WHEN x + y > z AND x + z > y AND y + z > x THEN'Yes' ELSE'No' ENDAS'triangle' FROM triangle ;
Consecutive Numbers - Medium
连续出现的数字:
1 2 3 4 5 6 7 8 9 10
Table: Logs
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | num | varchar | +-------------+---------+ id is the primary key for this table. id is an autoincrement column.
Input: Logs table: +----+-----+ | id | num | +----+-----+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 1 | | 6 | 2 | | 7 | 2 | +----+-----+ Output: +-----------------+ | ConsecutiveNums | +-----------------+ | 1 | +-----------------+ Explanation: 1 is the only number that appears consecutively for at least three times.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
-- MySQL SELECTDISTINCT l1.num AS ConsecutiveNums FROM Logs l1, Logs l2, Logs l3 WHERE l1.id = l2.id -1 AND l2.id = l3.id -1 AND l1.num = l2.num AND l2.num = l3.num ;
Product Price at a Given Date - Medium
指定日期的产品价格:
1 2 3 4 5 6 7 8 9 10
Table: Products
+---------------+---------+ | Column Name | Type | +---------------+---------+ | product_id | int | | new_price | int | | change_date | date | +---------------+---------+ (product_id, change_date) is the primary key
-- MySQL SELECT p1.product_id, IFNULL(p2.new_price, 10) AS price FROM ( SELECTDISTINCT product_id FROM products ) AS p1 LEFTJOIN ( SELECT product_id, new_price FROM products WHERE (product_id, change_date) IN ( SELECT product_id, MAX(change_date) FROM products WHERE change_date <='2019-08-16' GROUPBY product_id ) ) AS p2 ON p1.product_id = p2.product_id ;
Last Person to Fit in the Bus - Medium
最后一个能进入电梯的人:
1 2 3 4 5 6 7 8 9 10 11
Table: Queue
+-------------+---------+ | Column Name | Type | +-------------+---------+ | person_id | int | | person_name | varchar | | weight | int | | turn | int | +-------------+---------+ person_id is the primary key
-- MySQL -- 方法一:自连接 SELECT a.person_name FROM Queue a, Queue b WHERE a.turn >= b.turn GROUPBY a.person_id HAVINGSUM(b.weight) <=1000 ORDERBY a.turn DESC LIMIT 1 ;
-- 方法二:自定义变量 SELECT a.person_name FROM ( SELECT person_name, @pre :=@pre+ weight AS weight FROM queue, (SELECT@pre :=0) AS tmp ORDERBY turn ) AS a WHERE a.weight <=1000 ORDERBY a.weight DESC LIMIT 1 ;
Count Salary Categories - Medium
按分类统计薪水:
1 2 3 4 5 6 7 8 9
Table: Accounts
+-------------+------+ | Column Name | Type | +-------------+------+ | account_id | int | | income | int | +-------------+------+ account_id is the primary key
Output: +----------------+----------------+ | category | accounts_count | +----------------+----------------+ | Low Salary | 1 | | Average Salary | 0 | | High Salary | 3 | +----------------+----------------+ Explanation: Low Salary: Account 2. Average Salary: No accounts. High Salary: Accounts 3, 6, and 8.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
-- MySQL SELECT 'Low Salary' category, SUM(income <20000) accounts_count FROM accounts UNIONALL SELECT 'Average Salary', SUM(income >=20000AND income <=50000) FROM accounts UNIONALL SELECT 'High Salary', SUM(income >50000) FROM accounts ;
Employees Whose Manager Left the Company - Easy
上级经理已离职的公司员工
1 2 3 4 5 6 7 8 9 10 11 12 13
Table: Employees
+-------------+----------+ | Column Name | Type | +-------------+----------+ | employee_id | int | | name | varchar | | manager_id | int | | salary | int | +-------------+----------+
employee_id is the primary key Some employees do not have a manager (manager_id is null)
-- MySQL --方法一:左连接 select e1.employee_id from Employees e1 leftjoin Employees e2 on e1.manager_id = e2.employee_id where e1.salary <30000and e1.manager_id isnotnulland e2.employee_id isnull orderby e1.employee_id
--方法二:not in + 子查询 select employee_id from Employees where salary <30000 and manager_id notin (select employee_id from Employees) orderby employee_id
Exchange Seats - Medium
1 2 3 4 5 6 7 8 9 10
Table: Seat
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | student | varchar | +-------------+---------+ id is the primary key (unique value) column id is a continuous increment. 「连续增量」
-- MySQL 方法一:使用 CASE SELECT COUNT(*) AS counts FROM seat
SELECT (CASE WHENMOD(id, 2) !=0AND counts != id THEN id +1 WHENMOD(id, 2) !=0AND counts = id THEN id ELSE id -1 END) AS id, student FROM seat, (SELECT COUNT(*) AS counts FROM seat) AS seat_counts ORDERBY id ASC;
方法二:使用位操作和 COALESCE() SELECT id, (id+1)^1-1, student FROM seat;
SELECT * FROM seat s1 LEFTJOIN seat s2 ON (s1.id+1)^1-1= s2.id ORDERBY s1.id;
SELECT s1.id, COALESCE(s2.student, s1.student) AS student FROM seat s1 LEFTJOIN seat s2 ON ((s1.id +1) ^1) -1= s2.id ORDERBY s1.id;
+---------------+---------+ | Column Name | Type | +---------------+---------+ | movie_id | int | | title | varchar | +---------------+---------+ movie_id is the primary key
Table: Users
+---------------+---------+ | Column Name | Type | +---------------+---------+ | user_id | int | | name | varchar | +---------------+---------+ user_id is the primary key
Table: MovieRating
+---------------+---------+ | Column Name | Type | +---------------+---------+ | movie_id | int | | user_id | int | | rating | int | | created_at | date | +---------------+---------+ (movie_id, user_id) is the primary key
查找评论电影数量最多的用户名。如果出现平局,返回字典序较小的用户名。 查找在 February 2020 平均评分最高 的电影名称。如果出现平局,返回字典序较小的电影名称。