24. SQL data analysis practice (12 simple SQL questions)

Topic 1: E-commerce GMV analysis of "Double Eleven" campaign

Expansion: Gross Merchandise Volume (GMV for short) means the total amount of transactions (within a certain period of time). It is mostly used in the e-commerce industry, and generally includes taking pictures of unpaid order amounts.

There is an e-commerce GMV data table easy_gmv_info, which records the GMV data information of a merchant before and after the "Double Eleven" event. The data in the easy_gmv_info table is shown in the following table:

mysql> SELECT * FROM easy_gmv_info;
# date(日期): DATE  mall_gmv(GMV): INT 
+------------+----------+
| date       | mall_gmv |
+------------+----------+
| 2020-11-04 |    12325 |
| 2020-11-05 |    15497 |
| 2020-11-06 |    13216 |
| 2020-11-07 |    16548 |
| 2020-11-08 |    17367 |
| 2020-11-09 |    20124 |
| 2020-11-10 |    37325 |
| 2020-11-11 |   134367 |
| 2020-11-12 |    54331 |
| 2020-11-13 |    22212 |
| 2020-11-14 |    16312 |
| 2020-11-15 |    14384 |
| 2020-11-16 |    12314 |
| 2020-11-17 |    13146 |
+------------+----------+
14 rows in set (0.00 sec)

[Question 1] Query the change rate of GMV within a week from November 11, 2020 compared to 7 days ago. The output content includes: date (date), ratio (GMV change rate), and the result sample is shown in the figure below:
insert image description here
[Analysis of Question 1] Use the LAG() function to construct the data offset by 7 days, and obtain the difference gmv_diff by doing the difference. Then get the difference rate gmv_rate, then use the CONCAT() function to concatenate the % sign, and limit the result to November 11, 2020 to November 17, 2020 to get the final result. Knowledge points involved: subqueries, window functions, grouping and aggregation. The reference code is as follows:

SELECT `date`
     , CONCAT(gmv_rate, '%') AS ratio
FROM (
         SELECT `date`
              , mall_gmv
#               , (mall_gmv - LAG(mall_gmv, 7) OVER (ORDER BY `date`)) AS gmv_diff
              , (mall_gmv - LAG(mall_gmv, 7) OVER (ORDER BY `date`))
                    / LAG(mall_gmv, 7) OVER (ORDER BY `date`) * 100  AS gmv_rate
         FROM easy_gmv_info
     ) t
WHERE `date` BETWEEN '2020-11-11' AND '2020-11-17';

Topic 2: Website Traffic Analysis

There is a table of website visits, easy_website_visit, which records the daily visits of the website. The data of the easy_website_visit table is shown in the following table:

mysql> SELECT * FROM easy_website_visit;
-- data_content(日期访问量): VARCHAR 该字段的前8位为日期,后4位为访问量。
-- 例如: 201812011241 表示2018年12月01日的网站访问量为1241
+--------------+
| data_content |
+--------------+
| 201812011241 |
| 201812022493 |
| 201812030845 |
| 201812041230 |
| 201912012317 |
| 201912022520 |
| 201912031945 |
| 201912042031 |
| 202012013015 |
| 202012022914 |
| 202012032319 |
| 202012043143 |
+--------------+
12 rows in set (0.00 sec)

[Title 2] Query the maximum number of website visits per year (the corresponding date does not need to be output). The output includes: visit_year (visit year), max_visit (maximum number of visits), and the result sample is shown in the figure below:
insert image description here
[Analysis of Question 2] Use the SUBSTR() function to intercept the year and the number of visits in the data, and name them respectively visit_year and max_visit, and then use the RANK() function to group and rank in descending order according to the year, and take out the result ranked 1 outside the subquery, which is the maximum number of visits per year. Knowledge points involved: string processing functions, window functions, subqueries. The reference code is as follows:

-- 写法①
mysql> SELECT visit_year
    ->      , max_visit
    -> FROM (
    ->          SELECT SUBSTR(data_content, 1, 4)        AS visit_year
    ->               , SUBSTR(data_content, -4, 4)       AS max_visit
    ->               , RANK() OVER (PARTITION BY SUBSTR(data_content, 1, 4) ORDER
    ->              BY SUBSTR(data_content, -4, 4) DESC) AS ranking
    ->          FROM easy_website_visit
    -> #          ORDER BY data_content
    ->      ) a
    -> WHERE a.ranking = 1;

-- 写法②
SELECT b.visit_year, b.visit_num AS 'max_visit'
FROM (
         SELECT *, DENSE_RANK() OVER (PARTITION BY a.visit_year ORDER BY a.visit_num DESC ) AS visit_num_rank
         FROM (SELECT LEFT(data_content, 4) AS visit_year, RIGHT(data_content, 4) AS visit_num
               FROM easy_website_visit) a) b
WHERE b.visit_num_rank = 1;

Topic 3: User Shopping Information Statistics

There are two tables. The first table is easy_user_register_info, the user's registration information table on the shopping website. This table records the user's registration information on the shopping website. The data of the easy_user_register_info table is shown in the following table:

mysql> SELECT * from easy_user_register_info;
-- user_id(用户ID):VARCHAR register_date(用户注册日期):DATE
+---------+---------------+
| user_id | register_date |
+---------+---------------+
| a001    | 2020-10-15    |
| a002    | 2020-11-20    |
| a003    | 2020-12-13    |
| a004    | 2021-01-18    |
+---------+---------------+
4 rows in set (0.00 sec)

Another table is the user order information table easy_user_order_info, the data of the easy_user_order_info table is as follows:

mysql> SELECT * FROM easy_user_order_info;
-- user_id(用户ID):VARCHAR order_id(订单ID):VARCHAR order_date(订单日期):DATE commodity_id(商品ID):VARCHAR
+---------+----------+------------+--------------+
| user_id | order_id | order_date | commodity_id |
+---------+----------+------------+--------------+
| a001    | o001     | 2020-11-12 | c005         |
| a002    | o002     | 2020-12-27 | c003         |
| a002    | o003     | 2021-01-12 | c003         |
| a003    | o004     | 2021-02-25 | c001         |
| a004    | o005     | 2021-03-12 | c004         |
| a004    | o006     | 2021-03-14 | c005         |
+---------+----------+------------+--------------+
6 rows in set (0.00 sec)

[Title 3] Query the registration date of each user and the total number of orders in 2021. The output includes: user_id (user ID), reg_date (registration date), orders_2021 (the total number of orders in 2021), and the result sample is shown in the figure below: [Analysis of topic 3] LEFT the user order information table and registration information
insert image description here
table JOIN, you can get all order information (including user registration date), and then filter out users who have shopping orders in 2021, and group and count their total orders in 2021. Knowledge points involved: subqueries, window functions. The reference code is as follows:

mysql> SELECT aa.user_id
    ->      , aa.register_date
    ->      , IFNULL(bb.order_2021, 0) AS orders_2021
    -> FROM easy_user_register_info aa
    ->          LEFT JOIN
    ->      (
    ->          SELECT b.user_id
    ->               , b.register_date
    ->               , COUNT(order_id) AS order_2021
    ->          FROM easy_user_order_info a
    ->                   LEFT JOIN easy_user_register_info b
    ->                             ON a.user_id = b.user_id
    ->          WHERE YEAR(order_date) = 2021
    ->          GROUP BY b.user_id
    ->                 , b.register_date
    ->      ) bb
    ->      ON aa.user_id = bb.user_id;

Topic 4: Items sold consecutively

There is an information table easy_sold_succession of the user's shopping order on the e-commerce website. The information in this table is arranged in chronological order. The data in the easy_sold_succession table is as follows:

mysql> SELECT * FROM easy_sold_succession;
-- order_id(订单ID):INT commodity_id(购买的商品ID):VARCHAR
+----------+--------------+
| order_id | commodity_id |
+----------+--------------+
|        1 | c_001        |
|        2 | c_001        |
|        3 | c_002        |
|        4 | c_002        |
|        5 | c_002        |
|        6 | c_001        |
|        7 | c_003        |
|        8 | c_003        |
|        9 | c_003        |
|       10 | c_003        |
|       11 | c_001        |
+----------+--------------+
11 rows in set (0.00 sec)

【Question 4】Find the ID of the product that has been ordered more than or equal to 3 times in a row. The output includes: commodity_id (purchased commodity ID), the result sample is as follows:
insert image description here
[Problem 4 Analysis] Use the window function LAG(order_id,2) to group according to the commodity ID, and delay two lines in ascending order according to the default order order exhibit. Knowledge points involved: subquery, window function, DISTINCT. The SQL code for this question is as follows:

mysql> SELECT DISTINCT commodity_id
    -> FROM
    -> (
    ->  SELECT commodity_id
    ->  ,order_id
    ->  ,LAG(order_id,2) OVER (PARTITION BY commodity_id ORDER BY
    ->  order_id) AS temp
    ->  FROM easy_sold_succession
    -> )a
    -> WHERE order_id = temp + 2;

Topic 5: Swap even and odd positions

There is an existing student information table easy_student_info, and the data in the easy_student_info table is as follows:

-- student_id(学生学号):INT student_name(学生姓名):VARCHAR
mysql> SELECT * FROM easy_student_info;
+------------+--------------+
| student_id | student_name |
+------------+--------------+
|          1 | 李明         |
|          2 | 王猛         |
|          3 | 吴丽丽       |
|          4 | 张飞         |
|          5 | 赵涛         |
+------------+--------------+
5 rows in set (0.00 sec)

【Question 5】Swap adjacent students with odd numbers and even numbers. If the last one is an odd number, the student number will not be involved in the exchange, and the final result will be arranged in ascending order of the latest student number. The output includes: student_id (student number after exchange), student_name (student name), and the result sample is shown in the figure below Shown:
insert image description here
[Analysis of Topic 5] Use the MOD() function to divide the student number by 2, then judge the parity of the student number by the remainder, and combine the CASE WHEN statement, when the student number is odd, add 1 to the current student number to get The student's new student number; when the student number is even, subtract 1 from the current student number to get the student's new student number. Special case: when the current student number is the number of data entries and is odd, no operation will be performed on the student number. Knowledge points involved: subqueries, CASE WHEN, grouping aggregation, mathematical operation functions. The SQL code for this question is as follows:

mysql> SELECT CASE
    ->            WHEN MOD(student_id, 2) != 0 AND student_id != (SELECT COUNT(*) FROM easy_student_info)
    ->                THEN student_id + 1
    ->            WHEN MOD(student_id, 2) = 0 THEN student_id - 1
    ->            ELSE student_id
    ->            END AS student_id,
    ->        student_name
    -> FROM easy_student_info
    -> ORDER BY student_id ASC;

Topic 6: Product sales year-on-year

There is a commodity sales table easy_comparative_analysis, which records the monthly sales information of commodities. The data in the easy_comparative_analysis table is as follows:

mysql> SELECT * FROM easy_comparative_analysis;
-- month(月份)VARCHAR sales_volume(销量)INT
+---------+--------------+
| month   | sales_volume |
+---------+--------------+
| 2020-05 |          834 |
| 2020-06 |          604 |
| 2020-07 |          715 |
| 2020-08 |          984 |
| 2020-09 |         1024 |
| 2020-10 |          893 |
| 2020-11 |          485 |
| 2020-12 |          890 |
| 2021-01 |          563 |
| 2021-02 |          301 |
| 2021-03 |         1145 |
| 2021-04 |         1804 |
| 2021-05 |         1493 |
+---------+--------------+
13 rows in set (0.00 sec)

【题目6】Statistics of the year-on-year sales in May 2021. The output includes: sales_volume (sales in May 2021), year_ratio (year-on-year sales in May 2021), month_ratio (month-on-month sales in May 2021), and a sample of the results is shown in the figure below: [Analysis of Question 6] Using LAG(
insert image description here
) The function obtains the sales in May 2020 and April 2021 respectively as the year-on-year basis, calculates the year-on-year comparison, and outputs the year-on-year results in May 2021 through WHERE filtering. Knowledge points involved: subqueries, window functions. The SQL code for this question is as follows:

mysql> SELECT sales_volume
    ->      , CONCAT((sales_volume / year_on_year) * 100, '%')   AS year_ratio
    ->      -- 环比=(本期统计周期数据/上期统计周期数据)×100%
    ->      , CONCAT((sales_volume / month_on_month) * 100, '%') AS month_ratio
    -> FROM (SELECT `month`
    ->            , sales_volume
    ->            , LAG(sales_volume, 1) OVER (ORDER BY `month`)  AS month_on_month
    ->            , LAG(sales_volume, 12) OVER (ORDER BY `month`) AS year_on_year
    ->       FROM easy_comparative_analysis
    ->      ) a
    -> WHERE `month` = '2021-05';

Topic 7: Text record connection

There is an existing table easy_convert_table to be converted, and the data of the easy_convert_table table is shown in the following table:

mysql> SELECT * FROM easy_convert_table;
-- text_id(文本ID):VARCHAR text_content(文本内容):VARCHAR
+---------+--------------+
| text_id | text_content |
+---------+--------------+
| t001    | a            |
| t002    | b            |
| t001    | c            |
| t002    | d            |
| t002    | e            |
| t003    | f            |
+---------+--------------+
6 rows in set (0.00 sec)

[Question 7] Convert the table structure to the form shown in the figure below, that is, the text_content part of the same text_id is spliced ​​with the & symbol. The output includes: text_id (text ID), new_text (processed text), and the result sample is shown in the figure below:
insert image description here
[Analysis of Question 7] Use the GROUP_CONCAT() function to connect the text together, specify the connection symbol as &, and use grouping Aggregation joins records with the same text ID to get the result. Knowledge points involved: text processing functions, grouping and aggregation. The SQL code for this question is as follows:

mysql> SELECT text_id, GROUP_CONCAT(text_content SEPARATOR '&') AS 'new_text'
    -> FROM easy_convert_table
    -> GROUP BY text_id
    -> ORDER BY text_id;

Topic 8: Swap rows and columns

There is an information table easy_purchase_quantity of commodity purchase quantity in different quarters, and the data in the easy_purchase_quantity table is as follows:

mysql> SELECT * FROM easy_purchase_quantity;
-- year(年份):VARCHAR quarter(季度):VARCHAR amount(进货量):INT
+------+---------+--------+
| year | quarter | amount |
+------+---------+--------+
| 2019 | 1       |   1200 |
| 2019 | 2       |   1000 |
| 2019 | 3       |    800 |
| 2019 | 4       |   1300 |
| 2020 | 1       |   1100 |
| 2020 | 2       |    950 |
| 2020 | 3       |    700 |
| 2020 | 4       |   1050 |
+------+---------+--------+
8 rows in set (0.00 sec)

【题目8】Transform the above table structure into the form shown in the figure below. The output includes: year (year), first quarter, second quarter, third quarter, and fourth quarter commodity purchases.
insert image description here
[Analysis of Question 8] This question is a typical exchange of ranks and columns, and mainly examines the operation of CASE WHEN. Use the CASE WHEN statement to generate new fields for the first quarter to the fourth quarter, and group and aggregate by year to get the results. Knowledge points involved: CASE WHEN, group aggregation. The SQL code for this question is as follows:

mysql> SELECT year,
    ->        SUM(CASE WHEN quarter = 1 THEN amount ELSE 0 END) AS '一季度',
    ->        SUM(CASE WHEN quarter = 2 THEN amount ELSE 0 END) AS '二季度',
    ->        SUM(CASE WHEN quarter = 3 THEN amount ELSE 0 END) AS '三季度',
    ->        SUM(CASE WHEN quarter = 4 THEN amount ELSE 0 END) AS '四季度'
    -> FROM easy_purchase_quantity
    -> GROUP BY year;

Topic 9: Finding eligible orders

There is an order table easy_consumer_order for user consumption, and the data in the easy_consumer_order table is shown in the following table:

mysql> SELECT * FROM easy_consumer_order;
-- order_id(订单ID):VARCHAR money(订单金额):INT
+----------+-------+
| order_id | money |
+----------+-------+
| a001     |  2000 |
| a002     |  4000 |
| a003     |  6000 |
| a004     |  2000 |
| a005     |  4000 |
| a006     |  3000 |
| a007     |  2000 |
| a008     |  4000 |
| a009     |  5000 |
+----------+-------+
9 rows in set (0.00 sec)

[Question 9] Accumulate money in order of order ID, and obtain the order ID and minimum difference corresponding to the minimum difference between the cumulative value and 20000. If there are multiple eligible order IDs, take out the order corresponding to the minimum difference ID and minimum difference. The output includes: order_id (order ID), diff (minimum difference). A sample of the result is shown in the figure below:
insert image description here
[Analysis of Topic 9] Use the window function to calculate the absolute value of the difference between 20000 and the current cumulative money value and use it as a new column. After sorting the column in ascending order, use LIMIT to obtain the first item to got the answer. Knowledge points involved: window function. The SQL code for this question is as follows:

mysql> SELECT order_id, ABS(SUM(money) OVER (ORDER BY order_id) - 20000) AS 'diff'
    -> FROM easy_consumer_order
    -> ORDER BY diff ASC
    -> LIMIT 1;

Topic 10: Coupon Usage Analysis

There is an e-commerce coupon collection table easy_coupon_collection, which records the information of users receiving coupons. The data in the easy_coupon_collection table is shown in the following table:

mysql> SELECT * FROM easy_coupon_collection;
-- user_id(用户ID):VARCHAR collection_date(领取优惠券日期):DATE
+---------+-----------------+
| user_id | collection_date |
+---------+-----------------+
| u001    | 2021-05-01      |
| u002    | 2021-05-01      |
| u003    | 2021-05-02      |
| u004    | 2021-05-02      |
| u005    | 2021-05-03      |
+---------+-----------------+
5 rows in set (0.00 sec)

There is also an e-commerce consumption table easy_consumption_info, the data of the easy_consumption_info table is shown in the following table:

mysql> SELECT * FROM easy_consumption_info;
-- user_id(用户ID):VARCHAR consumption_date(消费日期):DATE
+---------+------------------+
| user_id | consumption_date |
+---------+------------------+
| u002    | 2021-04-28       |
| u001    | 2021-04-29       |
| u001    | 2021-05-03       |
| u003    | 2021-05-05       |
| u005    | 2021-05-06       |
| u001    | 2021-05-08       |
| u004    | 2021-05-09       |
| u006    | 2021-05-09       |
| u003    | 2021-05-10       |
| u002    | 2021-05-10       |
+---------+------------------+
10 rows in set (0.00 sec)

[Question 10] The coupon received by the user will take effect on the next day, and it will automatically take effect when shopping within the next 7 days, and the number of times it can be used is unlimited. It is required to obtain the users who have successfully consumed coupons and their corresponding consumption times. The output content includes: user_id (users who successfully used coupons to consume), num (consumption times). The result sample is shown in the figure below:
insert image description here
[Analysis of Question 10] Use INNER JOIN to join the two tables. The connection condition is that the user IDs are the same, and then use the DATE_DIFF() function to filter out the dates that meet the use of coupons, and filter the selected The result is grouped and counted to get the result. Knowledge points involved: group aggregation, date/time processing functions. The SQL code for this question is as follows:

mysql> -- 第①种写法
mysql> SELECT e1.user_id, COUNT(e2.consumption_date) AS num
    -> FROM easy_coupon_collection e1
    ->          INNER JOIN easy_consumption_info e2 ON e1.user_id = e2.user_id
    -> WHERE DATEDIFF(e2.consumption_date, e1.collection_date) BETWEEN 1 AND 7
    -> GROUP BY e1.user_id;
+---------+-----+
| user_id | num |
+---------+-----+
| u001    |   2 |
| u003    |   1 |
| u005    |   1 |
| u004    |   1 |
+---------+-----+
4 rows in set (0.00 sec)

mysql> -- 第②种写法
mysql> SELECT e1.user_id, COUNT(e2.consumption_date) AS num
    -> FROM easy_coupon_collection e1
    -> INNER JOIN easy_consumption_info e2 ON e1.user_id = e2.user_id 
AND e2.consumption_date BETWEEN DATE_ADD(e1.collection_date, INTERVAL 1 DAY) AND DATE_ADD(e1.collection_date, INTERVAL 7 DAY)
    -> GROUP BY e1.user_id;
+---------+-----+
| user_id | num |
+---------+-----+
| u001    |   2 |
| u003    |   1 |
| u005    |   1 |
| u004    |   1 |
+---------+-----+
4 rows in set (0.00 sec)

Topic 11: Employee Performance Appraisal

There is an employee performance scoring table easy_employee_performance, and the data in the easy_employee_performance table is as follows:

-- employee_id(员工ID):VARCHAR target_a(A指标)得分:INT target_b(B指标)得分:INT
-- target_c(C指标)得分:INT target_d(D指标)得分:INT target_e(E指标)得分:INT
mysql> SELECT * FROM easy_employee_performance;
+-------------+----------+----------+----------+----------+----------+
| employee_id | target_a | target_b | target_c | target_d | target_e |
+-------------+----------+----------+----------+----------+----------+
| u001        |        9 |        7 |        9 |       10 |        6 |
| u002        |        8 |        8 |        8 |        9 |       10 |
| u003        |       10 |       10 |       10 |        9 |        9 |
| u004        |        5 |        7 |        9 |        8 |        8 |
| u005        |        7 |        7 |        5 |        4 |        6 |
| u006        |       10 |        9 |       10 |        7 |        8 |
| u007        |        8 |        7 |        8 |        9 |        6 |
| u008        |        8 |        9 |       10 |       10 |        6 |
| u009        |        5 |        5 |        6 |        7 |        6 |
| u010        |       10 |       10 |       10 |        8 |        7 |
+-------------+----------+----------+----------+----------+----------+
10 rows in set (0.00 sec)

[Question 11] When evaluating employee performance, excellent employees can be selected according to the scores of the employees' five indicators. The requirement for an excellent employee is to have at least 4 index scores greater than or equal to 8 points. Query the ID and total score of outstanding employees, and sort them in descending order of the total score; if the total scores are the same, sort them in ascending order of employee ID. The output includes: employee_id (employee ID), total_score (total score). The sample result is shown in the figure below:
insert image description here
[Analysis of Question 11] Use CASE WHEN to count whether the 5 indicators are greater than or equal to 8 points, and record those that meet the conditions as 1 (retain the original score), and record those that do not meet the conditions as 0. Then sum the statistical results, if the sum result is greater than or equal to 4 (32) (meaning that it meets the conditions of excellent employees), then filter the results through WHERE, and construct a column for summing the 5 index scores, and follow The title requires sorting, and the result can be obtained. The SQL code for this question is as follows:

mysql> SELECT employee_id, total_score
    -> FROM (SELECT employee_id,
    ->              CASE WHEN target_a >= 8 THEN target_a ELSE 0 END     AS a,
    ->              CASE WHEN target_b >= 8 THEN target_b ELSE 0 END     AS b,
    ->              CASE WHEN target_c >= 8 THEN target_c ELSE 0 END     AS c,
    ->              CASE WHEN target_d >= 8 THEN target_d ELSE 0 END     AS d,
    ->              CASE WHEN target_e >= 8 THEN target_e ELSE 0 END     AS e,
    ->              target_a + target_b + target_c + target_d + target_e AS 'total_score'
    ->       FROM easy_employee_performance) temp_table
    -> WHERE (a + b + c + d + e) >= 32
    -> ORDER BY total_score DESC, employee_id ASC;

Topic 12: Find the most active users in the game

There is a game user battle information table easy_pk_info, which records information such as user battles. The data in the easy_pk_info table is shown in the following table:

mysql> SELECT * from easy_pk_info;
-- request_id(发起对战用户ID)VARCHAR accept_id(接受对战用户ID):VARCHAR accept_date(接受对战日期):DATE
+------------+-----------+-------------+
| request_id | accept_id | accept_date |
+------------+-----------+-------------+
| a001       | a002      | 2021-03-01  |
| a001       | a003      | 2021-03-01  |
| a001       | a004      | 2021-03-02  |
| a002       | a003      | 2021-03-02  |
| a005       | a003      | 2021-03-03  |
| a006       | a001      | 2021-03-04  |
| a004       | a003      | 2021-03-05  |
+------------+-----------+-------------+
7 rows in set (0.00 sec)

[Question 12] The number of battles of a user can reflect the user's game activity, and it is required to count the user ID with the most number of battles and the number of battles (only one result needs to be returned). The output includes: user_id (user ID), cnt (number of battles). The result sample is shown in the figure below:
insert image description here
[Explanation of topic 12] When counting user information, it is necessary to count the information of the users who initiate the battle and accept the battle, and use UNION ALL to connect, use GROUP BY to count the groups and then sort them in reverse order according to the number. The first record (that is, the user information with the most number of battles). The SQL code for this question is as follows:

mysql> SELECT user_id
    ->      , COUNT(*) AS cnt
    -> FROM (
    ->          SELECT request_id AS user_id
    ->          FROM easy_pk_info
    ->          UNION ALL
    ->          SELECT accept_id AS user_id
    ->          FROM easy_pk_info
    ->      ) a
    -> GROUP BY user_id
    -> ORDER BY cnt DESC
    -> LIMIT 1;
-- 返回多条
SELECT user_id, cnt
FROM (SELECT user_id, cnt, DENSE_RANK() OVER (ORDER BY cnt DESC) AS cnt_rank
      FROM (SELECT user_id, COUNT(user_id) AS 'cnt'
            FROM (SELECT request_id AS 'user_id'
                  FROM easy_pk_info
                  UNION ALL
                  SELECT accept_id
                  FROM easy_pk_info) a
            GROUP BY a.user_id) b) c
WHERE c.cnt_rank = 1;

So far, today's study is over. The author declares here that the author writes the article only to learn and communicate, and to let more readers who study the database avoid some detours, save time, and do not use it for other purposes. If there is any infringement, contact The blogger can be deleted. Thank you for reading this blog post, I hope this article can become a leader on your programming journey. Happy reading!


insert image description here

    A good book does not tire of reading a hundred times, and the child knows himself when he is familiar with the class. And if I want to be the most beautiful boy in the audience, I must persist in acquiring more knowledge through learning, change my destiny with knowledge, witness my growth with blogs, and prove that I am working hard with actions.
    If my blog is helpful to you, if you like the content of my blog, please 点赞, 评论,收藏 click three links! I heard that those who like it will not have bad luck, and they will be full of energy every day! If you really want to prostitute for nothing, then I wish you happy every day, welcome to visit my blog often.
 Coding is not easy, everyone's support is the motivation for me to persevere. Don't forget 关注me after you like it!

Guess you like

Origin blog.csdn.net/xw1680/article/details/130484800