CREATEFUNCTION getNthHighestSalary(N INT) RETURNSINT BEGIN SET N=N-1; RETURN ( # Write your MySQL query statement below. SELECTDISTINCT Salary FROM Employee ORDERBY Salary DESCLIMIT N, 1 ); END
# Oracle中 SELECT Score, DENSE_RANK() OVER (ORDERBY Score DESC) ASRank FROM Scores
# MySQL SELECT sa.Score, ( # 统计去重后的sb表中有比sa.Score大的个数 SELECTCOUNT(DISTINCT sb.Score) FROM Scores AS sb WHERE sb.Score >= sa.Score ) ASRank FROM Scores AS sa ORDERBY Score DESC;
# Write your MySQL query statement below SELECT L1.Num AS ConsecutiveNums FROMLogsAS L1, LogsAS L2, LogsAS L3 WHERE L1.Id = L2.Id-1 AND L2.Id = L3.Id-1 AND L1.Num = L2.Num AND L2.Num = L3.Num;
SELECT DepartmentId, MAX(Salary) FROM Employee GROUPBY DepartmentId
然后,把部门表和员工表联结,取出需要的信息
通过代码:
1 2 3 4 5 6 7
SELECT d.Name AS Department, e.Name AS Employee, e.Salary AS Salary FROM Employee AS e INNERJOIN Department AS d ON e.DepartmentId = d.Id WHERE (DepartmentId, Salary) IN ( SELECT DepartmentId, MAX(Salary) FROM Employee GROUPBY DepartmentId );
+--------------+---------+ | 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 for each player and date, how many games played so far by the player. That is, the total number of games played by the player until that date. Check the example for clarity.
The query result format is in the following example:
Result table: +-----------+------------+---------------------+ | player_id | event_date | games_played_so_far | +-----------+------------+---------------------+ | 1 | 2016-03-01 | 5 | | 1 | 2016-05-02 | 11 | | 1 | 2017-06-25 | 12 | | 3 | 2016-03-02 | 0 | | 3 | 2018-07-03 | 5 | +-----------+------------+---------------------+ For the player with id 1, 5 + 6 = 11 games played by 2016-05-02, and 5 + 6 + 1 = 12 games played by 2017-06-25. For the player with id 3, 0 + 5 = 5 games played by 2018-07-03. Note that for each player we only care about the days when the player logged in.
SELECT * FROM Activity AS A1 INNERJOIN Activity AS A2 ON (A1.player_id = A2.player_id AND A1.event_date <= A2.event_date)
再把玩家和该玩家在某个时期分组,求游戏个数之和。 通过代码:
1 2 3 4
SELECT A2.player_id, A2.event_date, SUM(A1.games_played) AS games_played_so_far FROM Activity AS A1 INNERJOIN Activity AS A2 ON (A1.player_id = A2.player_id AND A1.event_date <= A2.event_date) GROUPBY A2.player_id, A2.event_date;
+--------------+---------+ | 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 fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.
The query result format is in the following example:
Result table: +-----------+ | fraction | +-----------+ | 0.33 | +-----------+ Only the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33
SELECT * FROM Activity AS A INNERJOIN Activity AS B ON A.player_id = B.player_id ANDDATEDIFF(B.event_date, A.event_date) = 1 WHERE (A.player_id, A.event_date) IN ( SELECT player_id, MIN(event_date) FROM Activity GROUPBY player_id )
最后求出比例,用ROUND函数保留两位小数:
1 2 3 4 5 6 7 8
SELECTROUND(COUNT(DISTINCT B.event_date) / COUNT(DISTINCT A.player_id), 2) AS fraction FROM Activity AS A INNERJOIN Activity AS B ON A.player_id = B.player_id ANDDATEDIFF(B.event_date, A.event_date) = 1 WHERE (A.player_id, A.event_date) IN ( SELECT player_id, MIN(event_date) FROM Activity GROUPBY player_id )
570 Managers with at Least 5 Direct Reports 至少有5名直接下属的经理
The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.
+------+----------+-----------+----------+ |Id |Name |Department |ManagerId | +------+----------+-----------+----------+ |101 |John |A |null | |102 |Dan |A |101 | |103 |James |A |101 | |104 |Amy |A |101 | |105 |Anne |A |101 | |106 |Ron |B |101 | +------+----------+-----------+----------+ Given the Employee table, write a SQL query that finds out managers with at least 5 direct report. For the above table, your SQL query should return:
+-------+ | Name | +-------+ | John | +-------+ Note: No one would report to himself.
+-----+---------+ | id | Name | +-----+---------+ | 1 | A | | 2 | B | | 3 | C | | 4 | D | | 5 | E | +-----+---------+ Table: Vote
+-----+--------------+ | id | CandidateId | +-----+--------------+ | 1 | 2 | | 2 | 4 | | 3 | 3 | | 4 | 2 | | 5 | 5 | +-----+--------------+ id is the auto-increment primary key, CandidateId is the id appeared in Candidate table. Write a sql to find the name of the winning candidate, the above example will return the winner B.
+------+ | Name | +------+ | B | +------+ Notes:
You may assume there is no tie, in other words there will be at most one winning candidate.
SELECTName FROM Candidate WHEREidIN ( SELECT t.CandidateId FROM ( SELECT CandidateId FROM Vote GROUPBY CandidateId ORDERBYCOUNT(*) DESC LIMIT0,1 ) AS t );
注意IN ()内层的SELECT语句,需要额外嵌套一层,否则会报错: Error Code: 1235. This version of MySQL doesn’t yet support ‘LIMIT & IN/ALL/ANY/SOME subquery’
也可以这样写:
1 2 3 4 5 6 7 8 9 10
SELECT FROM Candidate AS C JOIN ( SELECT V.CandidateId, COUNT(V.id) AS cnt FROM Vote AS V GROUPBY CandidateId ORDERBY cnt DESC LIMIT0,1 ) AS T ON C.id = T.CandidateId;
Get the highest answer rate question from a table survey_log with these columns: uid, action, question_id, answer_id, q_num, timestamp.
uid means user id; action has these kind of values: "show", "answer", "skip"; answer_id is not null when action column is "answer", while is null for "show" and "skip"; q_num is the numeral order of the question in current session.
Write a sql query to identify the question which has the highest answer rate.
SELECT question_id AS survey_log FROM survey_log GROUPBY question_id ORDERBYSUM(IF(action='answer', 1, 0)) / SUM(IF(action='show', 1, 0)) DESC LIMIT0,1;
除了用SUM IF,还可以用CASE WHEN方法
1 2 3 4 5 6 7 8 9 10
SELECT question_id AS'survey_log' FROM ( SELECT question_id, SUM(CASEWHENaction='answer'THEN1ELSE0END) AS num_answer, SUM(CASEWHENaction='show'THEN1ELSE0END) AS num_show FROM survey_log GROUPBY question_id ) AS t ORDERBY (num_answer / num_show) DESC LIMIT0,1
A university uses 2 data tables, student and department, to store data about its students and the departments associated with each major.
Write a query to print the respective department name and number of students majoring in each department for all departments in the department table (even ones with no current students).
Sort your results by descending number of students; if two or more departments have the same number of students, then sort those departments alphabetically by department name.
The student is described as follow:
| Column Name | Type | |--------------|-----------| | student_id | Integer | | student_name | String | | gender | Character | | dept_id | Integer | where student_id is the student's ID number, student_name is the student's name, gender is their gender, and dept_id is the department ID associated with their declared major.
And the department table is described as below:
| Column Name | Type | |-------------|---------| | dept_id | Integer | | dept_name | String | where dept_id is the department's ID number and dept_name is the department name.
Here is an example input: student table:
| student_id | student_name | gender | dept_id | |------------|--------------|--------|---------| | 1 | Jack | M | 1 | | 2 | Jane | F | 1 | | 3 | Mark | M | 2 | department table:
| dept_id | dept_name | |---------|-------------| | 1 | Engineering | | 2 | Science | | 3 | Law | The Output should be:
SELECT D.dept_name, COUNT(S.student_id) AS student_number FROM department AS D LEFTJOIN student AS S ON D.dept_id = S.dept_id GROUPBY D.dept_name ORDERBY student_number DESC, D.dept_name;
Write a query to print the sum of all total investment values in 2016 (TIV_2016), to a scale of 2 decimal places, for all policy holders who meet the following criteria:
Have the same TIV_2015 value as one or more other policyholders. Are not located in the same city as any other policyholder (i.e.: the (latitude, longitude) attribute pairs must be unique). Input Format: The insurance table is described as follows:
| Column Name | Type | |-------------|---------------| | PID | INTEGER(11) | | TIV_2015 | NUMERIC(15,2) | | TIV_2016 | NUMERIC(15,2) | | LAT | NUMERIC(5,2) | | LON | NUMERIC(5,2) | where PID is the policyholder's policy ID, TIV_2015 is the total investment value in 2015, TIV_2016 is the total investment value in 2016, LAT is the latitude of the policy holder's city, and LON is the longitude of the policy holder's city.
The first record in the table, like the last record, meets both of the two criteria. The TIV_2015 value '10' is as the same as the third and forth record, and its location unique.
The second record does not meet any of the two criteria. Its TIV_2015 is not like any other policyholders.
And its location is the same with the third record, which makes the third record fail, too.
So, the result is the sum of TIV_2016 of the first and last record, which is 45.
SELECT TIV_2015 FROM insurance GROUPBY TIV_2015 HAVINGCOUNT(*) > 1;
第二条,(纬度,经度)必须唯一
1 2 3 4
SELECTCONCAT(LAT, LON) FROM insurance GROUPBY LAT,LON HAVINGCOUNT(*) = 1;
将符合这两个条件的TIV_2016值加起来,就是2016年的投资
通过代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
SELECTSUM(TIV_2016) AS TIV_2016 FROM insurance WHERE TIV_2015 IN ( SELECT TIV_2015 FROM insurance GROUPBY TIV_2015 HAVINGCOUNT(*) > 1 ) ANDCONCAT(LAT, LON) IN ( SELECTCONCAT(LAT, LON) FROM insurance GROUPBY LAT,LON HAVINGCOUNT(*) = 1 ) ;
602 Friend Requests II: Who Has the Most Friends 好友申请 II :谁有最多的好友
In social network like Facebook or Twitter, people send friend requests and accept others' requests as well.
Table request_accepted holds the data of friend acceptance, while requester_id and accepter_id both are the id of a person. | requester_id | accepter_id | accept_date| |--------------|-------------|------------| | 1 | 2 | 2016_06-03 | | 1 | 3 | 2016-06-08 | | 2 | 3 | 2016-06-08 | | 3 | 4 | 2016-06-09 | Write a query to find the the people who has most friends and the most friends number. For the sample data above, the result is: | id | num | |----|-----| | 3 | 3 | Note: It is guaranteed there is only 1 people having the most friends. The friend request could only been accepted once, which mean there is no multiple records with the same requester_id and accepter_id value.
Explanation: The person with id '3' is a friend of people '1', '2' and '4', so he has 3 friends in total, which is the most number than any others.
Follow-up: In the real world, multiple people could have the same most number of friends, can you find all these people in this case?
Given a table tree, id is identifier of the tree node and p_id is its parent node id.
+----+------+ | id | p_id | +----+------+ | 1 | null | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 2 | +----+------+ Each node in the tree can be one of three types: Leaf: if the node is a leaf node. Root: if the node is the root of the tree. Inner: If the node is neither a leaf node nor a root node.
Write a query to print the node id and the type of the node. Sort your output by the node id. The result for the above sample is:
Node '1' is root node, because its parent node is NULL and it has child node '2' and '3'. Node '2' is inner node, because it has parent node '1' and child node '4' and '5'. Node '3', '4' and '5' is Leaf node, because they have parent node and they don't have child node.
And here is the image of the sample tree as below:
1 / \ 2 3 / \ 4 5
Note: If there is only one node on the tree, you only need to output its root attributes.
SELECTid, 'Root'ASType FROM tree WHERE p_id ISNULL UNION SELECTid, 'Leaf'ASType FROM tree WHEREidNOTIN ( SELECT p_id FROM tree WHERE p_id ISNOTNULL ) UNION SELECTid, 'Inner'ASType FROM tree WHEREidIN ( SELECT p_id FROM tree WHERE p_id ISNOTNULL ) AND p_id ISNOTNULL ORDERBYid;
第二种方法,使用CASE WHEN语句来实现
1 2 3 4 5 6 7 8 9
SELECTid, ( CASEWHEN p_id ISNULLTHEN'Root' WHENidIN (SELECTDISTINCT p_id FROM tree) THEN'Inner' ELSE'Leaf' END ) AS Tpye FROM tree ORDERBYid;
第三种方法,把CASE WHEN换成IF语句
1 2 3
SELECTid, IF(ISNULL(p_id), 'Root', IF(idIN (SELECT p_id FROM tree), 'Inner', 'Leaf')) ASType FROM tree ORDERBYid;
612 Shortest Distance in a Plane 平面上的最近距离
题目描述:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Table point_2d holds the coordinates (x,y) of some unique points (more than two) in a plane.
Write a query to find the shortest distance between these points rounded to 2 decimals.
In facebook, there is a follow table with two columns: followee, follower.
Please write a sql query to get the amount of each follower’s follower if he/she has one.
For example:
+-------------+------------+ | followee | follower | +-------------+------------+ | A | B | | B | C | | B | D | | D | E | +-------------+------------+ should output: +-------------+------------+ | follower | num | +-------------+------------+ | B | 2 | | D | 1 | +-------------+------------+ Explaination: Both B and D exist in the follower list, when as a followee, B's follower is C and D, and D's follower is E. A does not exist in follower list.
Note: Followee would not follow himself/herself in all cases. Please display the result in follower's alphabet order.
+----------+----------+----------+----------+ | followee | follower | followee | follower | +----------+----------+----------+----------+ | A | B | B | C | | A | B | B | D | | B | D | D | E | +----------+----------+----------+----------+
那么接下来把这张表按关注者F1.follower分组,统计组内个数即num
通过代码:
1 2 3 4
SELECT F1.follower, COUNT(DISTINCT F2.follower) AS'num' FROM follow AS F1 INNERJOIN follow AS F2 ON F1.follower = F2.followee GROUPBY F1.follower;
+-------------+---------+ | Column Name | Type | +-------------+---------+ | customer_id | int | | product_key | int | +-------------+---------+ product_key is a foreign key to Product table. Table: Product
+-------------+---------+ | Column Name | Type | +-------------+---------+ | product_key | int | +-------------+---------+ product_key is the primary key column for this table.
Write an SQL query for a report that provides the customer ids from the Customer table that bought all the products in the Product table.
Result table: +-------------+ | customer_id | +-------------+ | 1 | | 3 | +-------------+ The customers who bought all the products (5 and 6) are customers with id 1 and 3.
+-------------+-------+ | 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 selects the product id, year, quantity, and price for the first year of every product sold.
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 most experienced employees in each project. In case of a tie, report all employees with the maximum number of experience years.
The query result format is in the following example:
Employee table: +-------------+--------+------------------+ | employee_id | name | experience_years | +-------------+--------+------------------+ | 1 | Khaled | 3 | | 2 | Ali | 2 | | 3 | John | 3 | | 4 | Doe | 2 | +-------------+--------+------------------+
Result table: +-------------+---------------+ | project_id | employee_id | +-------------+---------------+ | 1 | 1 | | 1 | 3 | | 2 | 1 | +-------------+---------------+ Both employees with id 1 and 3 have the most experience among the employees of the first project. For the second project, the employee with id 1 has the most experience.
解题思路:找出每个项目里工作经验最多的员工。先把项目表和员工表连接:
1 2 3 4
SELECT * FROMProjectAS P LEFTJOIN Employee AS E ON P.employee_id = E.employee_id ORDERBY P.project_id;
SELECT P.project_id, E.employee_id FROMProjectAS P LEFTJOIN Employee AS E ON P.employee_id = E.employee_id WHERE (P.project_id, E.experience_years) IN ( SELECT P.project_id, MAX(E.experience_years) FROMProjectAS P LEFTJOIN Employee AS E ON P.employee_id = E.employee_id GROUPBY P.project_id ) ;
Table: Books +----------------+---------+ | Column Name | Type | +----------------+---------+ | book_id | int | | name | varchar | | available_from | date | +----------------+---------+ book_id is the primary key of this table.
Table: Orders +----------------+---------+ | Column Name | Type | +----------------+---------+ | order_id | int | | book_id | int | | quantity | int | | dispatch_date | date | +----------------+---------+ order_id is the primary key of this table. book_id is a foreign key to the Books table.
Write an SQL query that reports the books that have sold less than 10 copies in the last year, excluding books that have been available for less than 1 month from today. Assume today is 2019-06-23.
The query result format is in the following example:
Result table: +-----------+--------------------+ | book_id | name | +-----------+--------------------+ | 1 | "Kalila And Demna" | | 2 | "28 Letters" | | 5 | "The Hunger Games" | +-----------+--------------------+
解题思路:找出去年到今天销量少于10的书id和名字,最近一个月才开始卖的除外。
先找出去年到今天,并且排除掉最近一个月的卖书情况:
1 2 3 4
SELECT * FROM books AS B LEFTJOIN orders AS O ON O.book_id = B.book_id AND O.dispatch_date BETWEEN'2018-06-23'AND'2019-06-23' WHEREDATEDIFF('2019-06-23', B.available_from) > 30;
SELECT B.book_id, B.name FROM books AS B LEFTJOIN orders AS O ON O.book_id = B.book_id AND O.dispatch_date BETWEEN'2018-06-23'AND'2019-06-23' WHEREDATEDIFF('2019-06-23', B.available_from) > 30 GROUPBY B.book_id HAVINGSUM(IF(O.quantity ISNULL, 0, O.quantity)) < 10;
+---------------+---------+ | Column Name | Type | +---------------+---------+ | user_id | int | | activity | enum | | activity_date | date | +---------------+---------+ There is no primary key for this table, it may have duplicate rows. The activity column is an ENUM type of ('login', 'logout', 'jobs', 'groups', 'homepage').
Write an SQL query that reports for every date within at most 90 days from today, the number of users that logged in for the first time on that date. Assume today is 2019-06-30.
The query result format is in the following example:
Result table: +------------+-------------+ | login_date | user_count | +------------+-------------+ | 2019-05-01 | 1 | | 2019-06-21 | 2 | +------------+-------------+ Note that we only care about dates with non zero user count. The user with id 5 first logged in on 2019-03-01 so he's not counted on 2019-06-21.
解题思路:先找出每个用户最早的登陆日期
1 2 3 4
SELECT user_id, MIN(activity_date) AS login_date FROM Traffic WHERE activity = 'login' GROUPBY user_id;
SELECT login_date, COUNT(user_id) AS user_count FROM ( SELECT user_id, MIN(activity_date) AS login_date FROM Traffic WHERE activity = 'login' GROUPBY user_id )AS t WHEREDATEDIFF('2019-06-30', login_date) <= 90 GROUPBY login_date;
+---------------+---------+ | Column Name | Type | +---------------+---------+ | student_id | int | | course_id | int | | grade | int | +---------------+---------+ (student_id, course_id) is the primary key of this table.
Write a SQL query to find the highest grade with its corresponding course for each student. In case of a tie, you should find the course with the smallest course_id. The output must be sorted by increasing student_id.
The query result format is in the following example:
+---------------+---------+ | Column Name | Type | +---------------+---------+ | business_id | int | | event_type | varchar | | occurences | int | +---------------+---------+ (business_id, event_type) is the primary key of this table. Each row in the table logs the info that an event of some type occured at some business for a number of times.
Write an SQL query to find all active businesses.
An active business is a business that has more than one event type with occurences greater than the average occurences of that event type among all businesses.
The query result format is in the following example:
Result table: +-------------+ | business_id | +-------------+ | 1 | +-------------+ Average for 'reviews', 'ads' and 'page views' are (7+3)/2=5, (11+7+6)/3=8, (3+12)/2=7.5 respectively. Business with id 1 has 7 'reviews' events (more than 5) and 11 'ads' events (more than 8) so it is an active business.
SELECT T.business_id FROM ( SELECT E.*, A.event_avg FROMEventsAS E LEFTJOIN ( SELECT event_type, AVG(occurences) AS event_avg FROMEvents GROUPBY event_type ) AS A ON E.event_type = A.event_type ) AS T WHERE T.occurences > T.event_avg GROUPBY T.business_id HAVINGCOUNT(T.event_type) > 1;
+---------------+---------+ | 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. Table: Removals
+---------------+---------+ | Column Name | Type | +---------------+---------+ | post_id | int | | remove_date | date | +---------------+---------+ post_id is the primary key of this table. Each row in this table indicates that some post was removed as a result of being reported or as a result of an admin review.
Write an SQL query to find the average for daily percentage of posts that got removed after being reported as spam, rounded to 2 decimal places.
The query result format is in the following example:
Result table: +-----------------------+ | average_daily_percent | +-----------------------+ | 75.00 | +-----------------------+ The percentage for 2019-07-04 is 50% because only one post of two spam reported posts was removed. The percentage for 2019-07-02 is 100% because one post was reported as spam and it was removed. The other days had no spam reports so the average is (50 + 100) / 2 = 75% Note that the output is only one number and that we do not care about the remove dates.
+---------------+---------+ | 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 people who viewed more than one article on the same date, sorted in ascending order by their id.
The query result format is in the following example:
SELECTDISTINCT t.id FROM ( SELECTCOUNT(DISTINCT article_id) AS articles, viewer_id asid FROM Views GROUPBY viewer_id, view_date ) AS t WHERE t.articles > 1 ORDERBY t.id;
+----------------+---------+ | Column Name | Type | +----------------+---------+ | user_id | int | | join_date | date | | favorite_brand | varchar | +----------------+---------+ user_id is the primary key of this table. This table has the info of the users of an online shopping website where users can sell and buy items. Table: Orders
+---------------+---------+ | Column Name | Type | +---------------+---------+ | order_id | int | | order_date | date | | item_id | int | | buyer_id | int | | seller_id | int | +---------------+---------+ order_id is the primary key of this table. item_id is a foreign key to the Items table. buyer_id and seller_id are foreign keys to the Users table. Table: Items
+---------------+---------+ | Column Name | Type | +---------------+---------+ | item_id | int | | item_brand | varchar | +---------------+---------+ item_id is the primary key of this table.
Write an SQL query to find for each user, the join date and the number of orders they made as a buyer in 2019.
The query result format is in the following example:
SELECT t.buyer_id, t.join_date, SUM(IF(YEAR(t.order_date)=2019, 1,0)) AS orders_id_2019 FROM ( SELECT O.buyer_id, O.order_date, U.join_date FROM Orders2 AS O LEFTJOINUsersAS U ON O.buyer_id = U.user_id GROUPBY O.buyer_id, O.order_date ) AS t GROUPBY t.buyer_id;
+---------------+---------+ | Column Name | Type | +---------------+---------+ | product_id | int | | new_price | int | | change_date | date | +---------------+---------+ (product_id, change_date) is the primary key of this table. Each row of this table indicates that the price of some product was changed to a new price at some date.
Write an SQL query to find the prices of all products on 2019-08-16. Assume the price of all products before any change is 10.
The query result format is in the following example:
+-----------------------------+---------+ | 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.
The first order of a customer is the order with the earliest order date that customer made. It is guaranteed that a customer has exactly one first order.
Write an SQL query to find the percentage of immediate orders in the first orders of all customers, rounded to 2 decimal places.
The query result format is in the following example:
Result table: +----------------------+ | immediate_percentage | +----------------------+ | 50.00 | +----------------------+ The customer id 1 has a first order with delivery id 1 and it is scheduled. The customer id 2 has a first order with delivery id 2 and it is immediate. The customer id 3 has a first order with delivery id 5 and it is scheduled. The customer id 4 has a first order with delivery id 7 and it is immediate. Hence, half the customers have immediate first orders.
+---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | country | varchar | | state | enum | | amount | int | | trans_date | date | +---------------+---------+ id is the primary key of this table. The table has information about incoming transactions. The state column is an enum of type ["approved", "declined"].
Write an SQL query to find for each month and country, the number of transactions and their total amount, the number of approved transactions and their total amount.
The query result format is in the following example:
Transactions table: +------+---------+----------+--------+------------+ | id | country | state | amount | trans_date | +------+---------+----------+--------+------------+ | 121 | US | approved | 1000 | 2018-12-18 | | 122 | US | declined | 2000 | 2018-12-19 | | 123 | US | approved | 2000 | 2019-01-01 | | 124 | DE | approved | 2000 | 2019-01-07 | +------+---------+----------+--------+------------+
+-------------+---------+ | Column Name | Type | +-------------+---------+ | person_id | int | | person_name | varchar | | weight | int | | turn | int | +-------------+---------+ person_id is the primary key column for this table. This table has the information about all people waiting for an elevator. The person_id and turn columns will contain all numbers from 1 to n, where n is the number of rows in the table.
The maximum weight the elevator can hold is 1000.
Write an SQL query to find the person_name of the last person who will fit in the elevator without exceeding the weight limit. It is guaranteed that the person who is first in the queue can fit in the elevator.
The query result format is in the following example:
Queue table +-----------+-------------------+--------+------+ | person_id | person_name | weight | turn | +-----------+-------------------+--------+------+ | 5 | George Washington | 250 | 1 | | 3 | John Adams | 350 | 2 | | 6 | Thomas Jefferson | 400 | 3 | | 2 | Will Johnliams | 200 | 4 | | 4 | Thomas Jefferson | 175 | 5 | | 1 | James Elephant | 500 | 6 | +-----------+-------------------+--------+------+
Result table +-------------------+ | person_name | +-------------------+ | Thomas Jefferson | +-------------------+
Queue table is ordered by turn in the example for simplicity. In the example George Washington(id 5), John Adams(id 3) and Thomas Jefferson(id 6) will enter the elevator as their weight sum is 250 + 350 + 400 = 1000. Thomas Jefferson(id 6) is the last person to fit in the elevator because he has the last turn in these three people.
SELECT *, ( SELECTSUM(weight) FROM Queue WHERE turn <= Q.turn ) AS leijia FROM Queue AS Q ORDERBY turn;
得到结果如下:
1 2 3 4 5 6 7 8 9 10
+-----------+-------------------+--------+------+--------+ | person_id | person_name | weight | turn | leijia | +-----------+-------------------+--------+------+--------+ | 5 | George Washington | 250 | 1 | 250 | | 3 | John Adams | 350 | 2 | 600 | | 6 | Thomas Jefferson | 400 | 3 | 1000 | | 2 | Will Johnliams | 200 | 4 | 1200 | | 4 | Thomas Jefferson | 175 | 5 | 1375 | | 1 | James Elephant | 500 | 6 | 1875 | +-----------+-------------------+--------+------+--------+
再以这张表为基础,找出leijia列值为1000的人的名字 通过代码:
1 2 3 4 5 6 7 8 9 10 11
SELECT person_name FROM ( SELECT *, ( SELECTSUM(weight) FROM Queue WHERE turn <= Q.turn ) AS leijia FROM Queue AS Q ) AS t WHERE t.leijia = 1000 ORDERBY turn;
+----------------+---------+ | Column Name | Type | +----------------+---------+ | id | int | | country | varchar | | state | enum | | amount | int | | trans_date | date | +----------------+---------+ id is the primary key of this table. The table has information about incoming transactions. The state column is an enum of type ["approved", "declined"]. Table: Chargebacks
+----------------+---------+ | Column Name | Type | +----------------+---------+ | trans_id | int | | charge_date | date | +----------------+---------+ Chargebacks contains basic information regarding incoming chargebacks from some transactions placed in Transactions table. trans_id is a foreign key to the id column of Transactions table. Each chargeback corresponds to a transaction made previously even if they were not approved.
Write an SQL query to find for each month and country, the number of approved transactions and their total amount, the number of chargebacks and their total amount.
Note: In your query, given the month and country, ignore rows with all zeros.
The query result format is in the following example:
Transactions table: +------+---------+----------+--------+------------+ | id | country | state | amount | trans_date | +------+---------+----------+--------+------------+ | 101 | US | approved | 1000 | 2019-05-18 | | 102 | US | declined | 2000 | 2019-05-19 | | 103 | US | approved | 3000 | 2019-06-10 | | 104 | US | approved | 4000 | 2019-06-13 | | 105 | US | approved | 5000 | 2019-06-15 | +------+---------+----------+--------+------------+
+---------------+----------+ | Column Name | Type | +---------------+----------+ | team_id | int | | team_name | varchar | +---------------+----------+ team_id is the primary key of this table. Each row of this table represents a single football team.
Table: Matches +---------------+---------+ | Column Name | Type | +---------------+---------+ | match_id | int | | host_team | int | | guest_team | int | | host_goals | int | | guest_goals | int | +---------------+---------+ match_id is the primary key of this table. Each row is a record of a finished match between two different teams. Teams host_team and guest_team are represented by their IDs in the teams table (team_id) and they scored host_goals and guest_goals goals respectively. You would like to compute the scores of all teams after all matches. Points are awarded as follows: A team receives three points if they win a match (Score strictly more goals than the opponent team). A team receives one point if they draw a match (Same number of goals as the opponent team). A team receives no points if they lose a match (Score less goals than the opponent team).
Write an SQL query that selects the team_id, team_name and num_points of each team in the tournament after all described matches. Result table should be ordered by num_points (decreasing order). In case of a tie, order the records by team_id (increasing order).
The query result format is in the following example:
Teams table: +-----------+--------------+ | team_id | team_name | +-----------+--------------+ | 10 | Leetcode FC | | 20 | NewYork FC | | 30 | Atlanta FC | | 40 | Chicago FC | | 50 | Toronto FC | +-----------+--------------+