SELECT CASEWHENMAX(Salary) ISNOTNULL THENMAX(Salary) ELSENULL ENDAS SecondHighestSalary FROM Employee WHERE Salary < ( SELECTMAX(Salary) FROM Employee );
再看关于题目讨论时候,发现CASE WHEN是多余的,可以省去,
简化后的通过代码:
1 2 3 4 5 6 7
SELECT MAX(Salary) AS SecondHighestSalary FROM Employee WHERE Salary < ( SELECTMAX(Salary) FROM Employee );
SELECT W2.Id AS Id FROM Weather AS W1, Weather AS W2 WHERE W2.Id = W1.Id + 1 AND W2.Temperature > W1.Temperature
这种写法报错是因为要考虑到日期为月末的情况,如果是31号,那么+1就是32号了,而不是次月1日。
正确思路:用datediff()函数来实现判断今天和昨天
通过代码:
1 2 3 4
SELECT W1.Id ASId FROM Weather AS W1 INNERJOIN Weather AS W2 ONDATEDIFF(W1.RecordDate, W2.RecordDate) = 1-- W1为今天的温度,W2为昨天的温度。 WHERE W1.Temperature > W2.Temperature;
关于datediff()函数的知识点:
DATEDIFF(expr1,expr2) DATEDIFF() returns expr1 − expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.
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 of this table. This table shows the activity of players of some game. Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.
Write an SQL query that reports the first login date for each player.
The query result format is in the following example:
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 of this table. This table shows the activity of players of some game.
Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.
Write a SQL query that reports the device that is first logged in for each player.
The query result format is in the following example:
SELECT A.player_id, A.device_id FROM Activity AS A WHERE (A.player_id, A.event_date) IN ( SELECT player_id, MIN(event_date) AS min_date FROM Activity GROUPBY player_id; )
或者也可以用内连接的方式:
1 2 3 4 5 6 7 8 9
SELECT A.player_id, A.device_id FROM Activity AS A INNERJOIN ( SELECT player_id, MIN(event_date) AS min_date FROM Activity GROUPBY player_id; ) AS B ON A.player_id = B.player_id AND A.event_date = B.min_date
Write a query to find the overall acceptance rate of requests rounded to 2 decimals, which is the number of acceptance divide the number of requests.
For the sample data above, your query should return the following result. |accept_rate| |-----------| | 0.80|
Note: The accepted requests are not necessarily from the table friend_request. In this case, you just need to simply count the total accepted requests (no matter whether they are in the original requests), and divide it by the number of requests to get the acceptance rate. It is possible that a sender sends multiple requests to the same receiver, and a request could be accepted more than once. In this case, the ‘duplicated’ requests or acceptances are only counted once. If there is no requests at all, you should return 0.00 as the accept_rate.
Explanation: There are 4 unique accepted requests, and there are 5 requests in total. So the rate is 0.80.
Follow-up: Can you write a query to return the accept rate but for every month? How about the cumulative accept rate for every day?
SELECT ROUND( IFNULL( -- 统计被接受的请求量,一个请求可能接受多次,但是统计时只算一次,因此去重 (SELECTCOUNT(*) FROM (SELECTDISTINCT requester_id, accepter_id FROM request_accepted) AS A) / -- 接受率 = 被接受的请求的数量 / 总的请求量 -- 统计总的请求量,一个人可能向同一人发送多次请求,只算一次,因此去重 (SELECTCOUNT(*) FROM (SELECTDISTINCT sender_id, send_to_id FROM friend_request) AS B) , 0) -- 如果没有请求,返回0.00作为接受率 , 2) -- round()函数保留两位小数 ) AS accept_rate;
思路:题目要求给出对’RED’公司没有销量的销售姓名,那么可以先找出对RED公司有销量的所有销售的姓名,然后使用NOT IN 排除掉这些人,剩下的就是对该公司没有销量的销售姓名。 在找对’RED’公司有销量的销售姓名时,需要将公司表company和订单表orders联结,并指定RED公司为过滤条件,找出销售员id。
通过代码:
1 2 3 4 5 6 7 8
SELECT s.name FROM salesperson AS s WHERE sales_id NOTIN ( SELECT o.sales_id FROM orders AS o LEFTJOIN company AS c ON o.com_id = c.com_id WHERE c.name = 'RED' );
+-------------+---------+ | Column Name | Type | +-------------+---------+ | actor_id | int | | director_id | int | | timestamp | int | +-------------+---------+ timestamp is the primary key column for this table.
Write a SQL query for a report that provides the pairs (actor_id, director_id) where the actor have cooperated with the director at least 3 times.
Result table: +-------------+-------------+ | actor_id | director_id | +-------------+-------------+ | 1 | 1 | +-------------+-------------+ The only pair is (1, 1) where they cooperated exactly 3 times.
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. Note that the price is per unit.
Table: Product +--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | +--------------+---------+ product_id is the primary key of this table.
Write an SQL query that reports all product names of the products in the Sales table along with their selling year and price.
Table: Sales +-------------+-------+ | Column Name | Type | +-------------+-------+ | sale_id | int | | product_id | int | | year | int | | quantity | int | | price | int | +-------------+-------+ sale_id is the primary key of this table. product_id is a foreign key to Product table. Note that the price is per unit.
Table: Product +--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | +--------------+---------+ product_id is the primary key of this table.
Write an SQL query that reports the total quantity sold for every product id.
The query result format is in the following example:
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 of this table.
Write an SQL query that reports the average experience years of all the employees for each project, rounded to 2 digits.
The query result format is in the following example:
Employee table: +-------------+--------+------------------+ | employee_id | name | experience_years | +-------------+--------+------------------+ | 1 | Khaled | 3 | | 2 | Ali | 2 | | 3 | John | 1 | | 4 | Doe | 2 | +-------------+--------+------------------+
Result table: +-------------+---------------+ | project_id | average_years | +-------------+---------------+ | 1 | 2.00 | | 2 | 2.50 | +-------------+---------------+ The average experience years for the first project is (3 + 2 + 1) / 3 = 2.00 and for the second project is (3 + 2) / 2 = 2.50
SELECT P.project_id, ROUND(AVG(E.experience_years), 2) AS average_years FROMProjectAS P INNERJOIN Employee AS E ON P.employee_id = E.employee_id GROUPBY P.project_id;
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 of this table.
Write an SQL query that reports all the projects that have the most employees.
The query result format is in the following example:
+--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | | unit_price | int | +--------------+---------+ product_id is the primary key of this table.
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 Product table. Write an SQL query that reports the best seller by total sales price, If there is a tie, report them all.
The query result format is in the following example:
Result table: +-------------+ | seller_id | +-------------+ | 1 | | 3 | +-------------+ Both sellers with id 1 and 3 sold products with the most total price of 2800.
Table: Product +--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | | unit_price | int | +--------------+---------+ product_id is the primary key of this table.
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 Product table.
Write an SQL query that reports the buyers who have bought S8 but not iPhone. Note that S8 and iPhone are products present in the Product table.
The query result format is in the following example:
Result table: +-------------+ | buyer_id | +-------------+ | 1 | +-------------+ The buyer with id 1 bought an S8 but didn't buy an iPhone. The buyer with id 3 bought both.
SELECTDISTINCT S.buyer_id FROM Sales AS S LEFTJOIN Product AS P ON S.product_id = P.product_id WHERE P.product_name = 'S8' AND S.buyer_id NOTIN ( SELECT S.buyer_id FROM Sales AS S LEFTJOIN Product AS P ON S.product_id = P.product_id WHERE P.product_name = 'iPhone' )
Table: Product +--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | | unit_price | int | +--------------+---------+ product_id is the primary key of this table.
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 Product table. Write an SQL query that reports the products that were only sold in spring 2019. That is, between 2019-01-01 and 2019-03-31 inclusive.
The query result format is in the following example:
Result table: +-------------+--------------+ | product_id | product_name | +-------------+--------------+ | 1 | S8 | +-------------+--------------+ The product with id 1 was only sold in spring 2019 while the other two were sold after.
SELECTDISTINCT P.product_id, P.product_name FROM Sales AS S LEFTJOIN Product AS P ON S.product_id = P.product_id WHERE S.sale_date BETWEEN'2019-01-01'AND'2019-03-31' AND P.product_id NOTIN ( SELECT P.product_id FROM Sales AS S LEFTJOIN Product AS P ON S.product_id = P.product_id WHERE S.sale_date NOTBETWEEN'2019-01-01'AND'2019-03-31' )
SELECTDISTINCT P.product_id, P.product_name FROM Product AS P INNERJOIN Sales AS A ON P.product_id = A.product_id LEFTJOIN ( SELECTDISTINCT S.product_id FROM Sales AS S WHERE S.sale_date NOTBETWEEN'2019-01-01'AND'2019-03-31'
) AS B ON A.product_id = B.product_id WHERE B.product_id ISNULL;
Table: Actions +---------------+---------+ | Column Name | Type | +---------------+---------+ | user_id | int | | post_id | int | | action_date | date | | action | enum | | extra | varchar | +---------------+---------+ There is no primary key for this table, it may have duplicate rows.
The action column is an ENUM type of ('view', 'like', 'reaction', 'comment', 'report', 'share').
The extra column has optional information about the action such as a reason for report or a type of reaction.
Write an SQL query that reports the number of posts reported yesterday for each report reason. Assume today is 2019-07-05.
The query result format is in the following example:
Result table: +---------------+--------------+ | report_reason | report_count | +---------------+--------------+ | spam | 1 | | racism | 2 | +---------------+--------------+ Note that we only care about report reasons with non zero number of reports.
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. The activity_type column is an ENUM of type ('open_session', 'end_session', 'scroll_down', 'send_message'). The table shows the user activities for a social media website. Note that each session belongs to exactly one user.
Write an SQL query to find the daily active user count for a period of 30 days ending 2019-07-27 inclusively. A user was active on some day if he/she made at least one activity on that day.
The query result format is in the following example:
Result table: +------------+--------------+ | day | active_users | +------------+--------------+ | 2019-07-20 | 2 | | 2019-07-21 | 2 | +------------+--------------+ Note that we do not care about days with zero active users.
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. The activity_type column is an ENUM of type ('open_session', 'end_session', 'scroll_down', 'send_message'). The table shows the user activities for a social media website. Note that each session belongs to exactly one user.
Write an SQL query to find the average number of sessions per user for a period of 30 days ending 2019-07-27 inclusively, rounded to 2 decimal places. The sessions we want to count for a user are those with at least one activity in that time period.
The query result format is in the following example:
Result table: +---------------------------+ | average_sessions_per_user | +---------------------------+ | 1.33 | +---------------------------+ User 1 and 2 each had 1 session in the past 30 days while user 3 had 2 sessions so the average is (1 + 1 + 2) / 3 = 1.33.
Table: Views +---------------+---------+ | Column Name | Type | +---------------+---------+ | article_id | int | | author_id | int | | viewer_id | int | | view_date | date | +---------------+---------+ There is no primary key for this table, it may have duplicate rows. Each row of this table indicates that some viewer viewed an article (written by some author) on some date. Note that equal author_id and viewer_id indicate the same person.
Write an SQL query to find all the authors that viewed at least one of their own articles, sorted in ascending order by their id.
The query result format is in the following example:
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 of this table. The table holds information about food delivery to customers that make orders at some date and specify a preferred delivery date (on the same order date or after it).
If the preferred delivery date of the customer is the same as the order date then the order is called immediate otherwise it's called scheduled.
Write an SQL query to find the percentage of immediate orders in the table, rounded to 2 decimal places.
The query result format is in the following example:
Result table: +----------------------+ | immediate_percentage | +----------------------+ | 33.33 | +----------------------+ The orders with delivery id 2 and 3 are immediate while the others are scheduled.