High-frequency practical interview questions from major SQL manufacturers in 2023 (detailed analysis)

Hello everyone, my name is Ning Yi.

I haven't had a break for four consecutive weeks. Recently, my main business and sideline business are at their peak. I get home from get off work at 11:00 in the evening, and then I write classes until 2:00 in the morning.

For more than a month, my biggest wish every day is to get enough sleep.

This stage is finally over~ Continue to update the SQL interview questions~

Topic five:

175. Combine two tables (simple)

Now there are two tables:

Person table: contains PersonId,

Information about last name LastName and first name FirstName.

+----------+----------+-----------+| personId | lastName | firstName |+----------+----------+-----------+|    1     | Wang     | Allen     ||    2     | Alice    | Bob       |+----------+----------+-----------+

Address table: contains AddressId, PersonId, City, and State information.

+-----------+----------+---------------+------------+| addressId | personId | city          | state      |+-----------+----------+---------------+------------+|   1      |    2     | New York City | New York   ||    2     |    3     | Leetcode      | California |+-----------+----------+---------------+------------+

Write a SQL query to report the last name, first name, city, and state of each person in the Person table. Reports as null if the personId's address is not in the Address table.

Example of results:​​​​​​​

+-----------+----------+---------------+----------+| firstName | lastName | city          | state    |+-----------+----------+---------------+----------+| Allen     | Wang     | Null          | Null     || Bob       | Alice    | New York City | New York |+-----------+----------+---------------+----------+

Problem-solving ideas:

This question is very simple. The main investigation is the knowledge points of JOIN connection, whether to use left connection or right connection.

Note the sentence in the title "If the address of personId is not in the Address table, the report is empty null ".

Null values ​​appear in the Address table, so we put the Person table on the left and the Address table on the right, using a left join. ​​​​​​​

SELECT firstName,lastName,city,stateFROM Person pLEFT JOIN Address aON p.personId = a.personId;

If you want to test locally on your own computer, you can use this to quickly create a data table statement:​​​​​​​​

-- 创建表Person CREATE TABLE Person(personId INT,LastName VARCHAR(10),FirstName VARCHAR(10));-- 插入语句INSERT INTO Person VALUES(1,'Wang','Allen'),(2,'Alice','Bob');CREATE TABLE Address(addressId INT,personId INT,City VARCHAR(20),state VARCHAR(20));-- 插入语句INSERT INTO Address VALUES(1,2,'New York City','New York'),(2,3,'Leetcode','California');

Knowledge point: Join connection

Joint query of multiple data tables requires the use of JOIN connection. There are several types of JOIN connection:

INNER JOIN : Inner connection, you can also just write JOIN. Only data that matches the connection criteria will be retained in the two tables being joined, which is equivalent to the intersection of the two tables. If you join the same table before and after, it is also called a self-join.

LEFT JOIN : Left join, also called left outer join. All records in the table on the left side of the operator that match the WHERE clause will be returned. If there are no records in the table on the right side of the operator that match the join conditions after ON, then the value of the selected column from the table on the right side will be NULL.

RIGHT JOIN : Right join, also called right outer join. All records matching the WHERE clause in the right table will be returned. The unmatched field values ​​in the left table are replaced by NULL.

*   FULL JOIN : full connection, return all records in all tables that meet the conditions of the WHERE statement. If there is no qualified value in the specified field of any table, then use NULL instead.

Topic six:

178. Score Ranking (Medium)

There is a score table: Scores​​​​​​​

+----+-------+| id | score |+----+-------+| 1  | 3.50  ||  2 | 3.65  || 3  | 4.00  || 4  | 3.85  || 5  | 4.00  || 6  | 3.65  |+----+-------+

Write a SQL query that sorts the scores from high to low, and if two scores are equal, then both scores should rank the same. It is required that the rankings should be continuous and there should be no vacant numbers in the middle.

The query result format is as follows. ​​​​​​​

+-------+------+| score | rank |+-------+------+| 4.00  | 1    || 4.00  | 1    || 3.85  | 2    || 3.65  | 3    || 3.65  | 3    || 3.50  | 4    |+-------+------+

Problem-solving ideas:

This question mainly examines "correlated subqueries". In correlated subqueries, subqueries are performed sequentially at the level of each record of the main query, and the subqueries depend on the main query.

For this question, we first sort the scores in reverse order, write the rank column as a subquery, and calculate the number of duplicates that are greater than or equal to the current outer query score. This number is the ranking.

Step 1 : First sort the scores in descending order. ​​​​​​​

SELECT a.Score AS '成绩'FROM Scores aORDER BY a.score DESC

Step 2 : Write the "ranking" column after select as a subquery. Calculate the number of duplicates that are greater than or equal to the current external query score. This number is the ranking. ​​​​​​​

SELECT a.Score AS '成绩',    (SELECT COUNT(DISTINCT score)    FROM Scores    WHERE score >= a.score) AS '排名'FROM Scores aORDER BY a.score DESC

If you want to test locally on your own computer, you can use this to quickly create a data table statement:​​​​​​​​

-- 创建表CREATE TABLE Scores(Id INT,score  DECIMAL(10,2));-- 插入语句INSERT INTO Scores VALUES(1,3.50),(2,3.65),(3,4.00),(4,3.85),(5,4.00),(6,3.65);

Topic 7:

183. Customers who never order (easy)

A website contains two tables, Customers and Orders. Write a SQL query to find all customers who never order anything.

Customers table:​​​​​​​​

+----+-------+| Id | Name  |+----+-------+| 1  | Joe   || 2  | Henry || 3  | Sam   || 4  | Max   |+----+-------+

Orders table:​​​​​​​

+----+------------+| Id | CustomerId |+----+------------+| 1  | 3          || 2  | 1          |+----+------------+

For example, given the above table, your query should return:​​​​​​​​

+-----------+| Customers |+-----------+| Henry     || Max       |+-----------+

Problem-solving ideas:

This question examines a subquery. If we want to find out the customers who have not ordered before, we first find out the customers who have already ordered in the Orders table, and then exclude these customers from the Customers table. It is very easy. Know who has never ordered.

Step 1 : First, find the customers who have already ordered in the order table Orders

SELECT customeridFROM orders

Step 2 : Use NOT IN to query customers who are not in this list. ​​​​​​​

SELECT name AS '未订购客户'FROM customersWHERE id NOT IN(SELECT customeridFROM orders);

If you want to test locally on your own computer, you can use this to quickly create a data table statement:​​​​​​​​

-- 创建表CREATE TABLE Customers(Id INT,Name VARCHAR(10));-- 插入语句INSERT INTO Customers VALUES(1,'Joe'),(2,'Henry'),(3,'Sam'),(4,'Max');CREATE TABLE Orders(Id INT,CustomerId INT);-- 插入语句INSERT INTO Orders VALUES(1,3),(2,1);

Topic 8:

184. Highest paid employee in the department (medium)

There are now two tables, the employee information table Employee and the department table Department.

Write a SQL query to find the top three paid employees in each department. Returns a table of results in any order.

Employee table:​​​​​​​​

+----+--------+--------+--------------+| id | name   | salary | departmentId |+----+--------+--------+--------------+| 1  | Joe    | 85000  |   1          || 2  | Henry  | 80000  |   2          || 3  | Sam    | 60000  |   2          || 4  | Max    | 90000  |   1          || 5  | Janet  | 69000  |   1          || 6  | Randy  | 85000  |   1          || 7  | Will   | 70000  |   1          |+----+---------+---------+------------+

Department table:​​​​​​​​

+------+---------+| id   | name    |+------+---------+| 1    |   IT    || 2    |   Sales |+------+---------+

Output example:

+------------+----------+--------+| Department | Employee | Salary |+------------+----------+--------+| IT         | Jim      | 90000  || Sales      | Henry    | 80000  || IT         | Max      | 90000  |+------------+----------+--------+

Problem-solving ideas:

This question examines table joins and subqueries.

We first group the departments into groups and find out the maximum salary corresponding to each department. Then put this query result after the Where statement, combined with the IN statement, to query the relationship between department name and salary.

It should be noted that a department may have multiple employees with the highest salary at the same time, so do not include employee name information in the subquery.

Step 1 : First, group the DepartmentId field in the employee table Employee to get the maximum salary value of each department.

SELECT DepartmentId, MAX( Salary )FROM EmployeeGROUP BY DepartmentId

Step two :

Then connect the employee table Employee and the department table Department through the DepartmentId field. After the connection is completed, find the names of all corresponding employees based on the department ID (DepartmentId) found in the previous step and the corresponding maximum salary. ​​​​​​​

SELECT  d.name AS 'Department',  e.name AS 'Employee',  SalaryFROM Employee eJOIN Department dON e.DepartmentId = d.IdWHERE (e.DepartmentId , Salary) IN  (    SELECT DepartmentId, MAX(Salary)    FROM  Employee    GROUP BY DepartmentId  );

If you want to test locally on your own computer, you can use this to quickly create a data table statement:​​​​​​​​

-- 创建表CREATE TABLE Employee(id INT,name VARCHAR(10),salary INT,departmentId INT);-- 插入语句INSERT INTO Employee VALUES(1,'Joe',70000,1),(2,'Jim',90000,1),(3,'Henry',80000,2),(4,'Sam',60000,2),(5,'Max',90000,1);CREATE TABLE Department(id INT,name VARCHAR(20));-- 插入语句INSERT INTO Department VALUES(1,'IT'),(2,'Sales’);

Knowledge points:

(1) Aggregation function:

Aggregation functions, as the name suggests, are functions that aggregate data records together.

For example, there are 100 records in the original database. If you use an aggregate function to query the maximum value among these 100 records, only the record with the maximum value will be output.

Commonly used aggregate functions include:

MAX( ) maximum value

MIN( ) minimum value

SUM( ) total value

AVG( ) average

COUNT( ) number of records

(2) Subquery:

SQL statements can be nested, and the most common one is the nesting of query statements. We generally call the outer nested statement the main query, and the inner nested statement a subquery.

(3) group by group :

The GROUP BY clause is used to group result sets and is usually used in conjunction with aggregate functions.

Guess you like

Origin blog.csdn.net/shine_a/article/details/128567887