当前位置:网站首页>Tutorial on principles and applications of database system (052) -- data integrity of MySQL (XIV): crosstab query (row column conversion)
Tutorial on principles and applications of database system (052) -- data integrity of MySQL (XIV): crosstab query (row column conversion)
2022-07-24 00:51:00 【Rsda DBA_ WGX】
Database system principle and Application Tutorial (052)—— MySQL Data integrity ( fourteen ): Crosstab query ( Row column conversion )
Catalog
Crosstab query is to group the columns in the table , A set of columns is on the left side of the crosstab , A group is listed at the top of the crosstab , Various calculated values of a field in the table are displayed at the intersection of rows and columns in the cross table .
Crosstab is divided into static crosstab and dynamic crosstab . The columns in the static crosstab are fixed , Moreover, the data content in the column to be converted into row and column should be determined in advance , Insufficient flexibility in use . The columns in the dynamic crosstab are dynamically generated according to the data in the columns to be converted into rows and columns , There is no need to determine the data content of this column in advance , You don't even need to know what the data in this column is .
Use crosstab queries to calculate and reconstruct data , It can simplify data analysis . Crosstab query calculates the sum of data , Average , Counting and other types of Statistics , And group them , A set of columns are on the left side of the data table as row fields of the crosstab , Another group of columns is at the top of the data table as the column fields of the crosstab .
One 、 In the form of a crosstab
Crosstab query is also called row column conversion , Is to convert the following query results into tables 1( Crossover table ).
/* select s.s_id, s.s_name, c.c_id, c.c_name, sc.score from student s,course c,score sc where s.s_id=sc.s_id and c.c_id=sc.c_id; */
mysql> select s.s_id, s.s_name, c.c_id, c.c_name, sc.score
-> from student s,course c,score sc where s.s_id=sc.s_id and c.c_id=sc.c_id;
+-------+-----------+------+--------------+-------+
| s_id | s_name | c_id | c_name | score |
+-------+-----------+------+--------------+-------+
| S2011 | Zhang Xiaogang | C102 | Advanced mathematics | 84 |
| S2011 | Zhang Xiaogang | C105 | Infectious diseases | 90 |
| S2012 | Liu Xiaoqing | C101 | Ancient literature | 67 |
| S2012 | Liu Xiaoqing | C102 | Advanced mathematics | 52 |
| S2012 | Liu Xiaoqing | C103 | linear algebra | 55 |
| S2012 | Liu Xiaoqing | C104 | Clinical medicine | 86 |
| S2012 | Liu Xiaoqing | C105 | Infectious diseases | 87 |
| S2013 | Cao mengde | C102 | Advanced mathematics | 97 |
| S2013 | Cao mengde | C103 | linear algebra | 68 |
| S2013 | Cao mengde | C104 | Clinical medicine | 66 |
| S2013 | Cao mengde | C105 | Infectious diseases | 68 |
| S2014 | Liu Yan | C102 | Advanced mathematics | 90 |
| S2014 | Liu Yan | C103 | linear algebra | 85 |
| S2014 | Liu Yan | C104 | Clinical medicine | 77 |
| S2014 | Liu Yan | C105 | Infectious diseases | 96 |
| S2015 | Liu Yan | C101 | Ancient literature | 69 |
| S2015 | Liu Yan | C102 | Advanced mathematics | 66 |
| S2015 | Liu Yan | C103 | linear algebra | 88 |
| S2015 | Liu Yan | C104 | Clinical medicine | 69 |
| S2015 | Liu Yan | C105 | Infectious diseases | 66 |
| S2016 | Liu Ruofei | C101 | Ancient literature | 65 |
| S2016 | Liu Ruofei | C102 | Advanced mathematics | 69 |
| S2021 | Dong Wenhua | C102 | Advanced mathematics | 72 |
| S2021 | Dong Wenhua | C103 | linear algebra | 90 |
| S2021 | Dong Wenhua | C104 | Clinical medicine | 90 |
| S2021 | Dong Wenhua | C105 | Infectious diseases | 57 |
| S2022 | Zhou Huajian | C102 | Advanced mathematics | 88 |
| S2022 | Zhou Huajian | C103 | linear algebra | 93 |
| S2023 | trump | C102 | Advanced mathematics | 68 |
| S2023 | trump | C103 | linear algebra | 86 |
| S2024 | Obama | C102 | Advanced mathematics | 87 |
| S2024 | Obama | C103 | linear algebra | 97 |
| S2025 | Zhou Jianhua | C102 | Advanced mathematics | 61 |
| S2025 | Zhou Jianhua | C105 | Infectious diseases | 62 |
| S2026 | Zhang Xueyou | C102 | Advanced mathematics | 59 |
| S2026 | Zhang Xueyou | C105 | Infectious diseases | 48 |
+-------+-----------+------+--------------+-------+
36 rows in set (0.00 sec)
-- surface 1( Crossover table )
+-----------+------------+------------+------------+-------------+-------------+--------+
| s_name | Ancient literature | Advanced mathematics | linear algebra | Clinical medicine | Infectious diseases | Total score |
+-----------+------------+------------+------------+-------------+-------------+--------+
| Liu Xiaoqing | 67 | 52 | 55 | 86 | 87 | 347 |
| Liu Yan | 69 | 156 | 173 | 146 | 16 | 706 |
| Liu Ruofei | 65 | 69 | Not elective | Not elective | Not elective | 134 |
| Zhou Jianhua | Not elective | 61 | Not elective | Not elective | 62 | 123 |
| Zhou Huajian | Not elective | 88 | 93 | Not elective | Not elective | 181 |
| Obama | Not elective | 87 | 97 | Not elective | Not elective | 184 |
| Zhang Xueyou | Not elective | 59 | Not elective | Not elective | 48 | 107 |
| Zhang Xiaogang | Not elective | 84 | Not elective | Not elective | 90 | 174 |
| Cao mengde | Not elective | 97 | 68 | 66 | 68 | 299 |
| trump | Not elective | 68 | 86 | Not elective | Not elective | 154 |
| Dong Wenhua | Not elective | 72 | 90 | 90 | 57 | 309 |
+-----------+-------------+-----------+-------------+-------------+-------------+--------+
Two 、 Static crosstab
The basic method of generating crosstab is :
(1) Group according to the row fields of the crosstab ( such as s_name).
(2) For row fields to be converted to columns ( such as c_name) Make statistics , Use in statistical functions IF Function to filter the data , Generate column fields .
The cross table query code is as follows :
/* select ifnull(s_name,' Total score ') full name , if(sum(if(c.c_id='C101',score,0))=0,' Not elective ',sum(if(c.c_id='C101',score,0))) Ancient literature , if(sum(if(c.c_id='C102',score,0))=0,' Not elective ',sum(if(c.c_id='C102',score,0))) Advanced mathematics , if(sum(if(c.c_id='C103',score,0))=0,' Not elective ',sum(if(c.c_id='C103',score,0))) linear algebra , if(sum(if(c.c_id='C104',score,0))=0,' Not elective ',sum(if(c.c_id='C104',score,0))) Clinical medicine , if(sum(if(c.c_id='C105',score,0))=0,' Not elective ',sum(if(c.c_id='C105',score,0))) Infectious diseases , sum(score) Total score from student s,course c,score sc where s.s_id=sc.s_id and c.c_id=sc.c_id group by s_name with rollup; */
mysql> select ifnull(s_name,' Total score ') full name ,
-> if(sum(if(c.c_id='C101',score,0))=0,' Not elective ',sum(if(c.c_id='C101',score,0))) Ancient literature ,
-> if(sum(if(c.c_id='C102',score,0))=0,' Not elective ',sum(if(c.c_id='C102',score,0))) Advanced mathematics ,
-> if(sum(if(c.c_id='C103',score,0))=0,' Not elective ',sum(if(c.c_id='C103',score,0))) linear algebra ,
-> if(sum(if(c.c_id='C104',score,0))=0,' Not elective ',sum(if(c.c_id='C104',score,0))) Clinical medicine ,
-> if(sum(if(c.c_id='C105',score,0))=0,' Not elective ',sum(if(c.c_id='C105',score,0))) Infectious diseases ,
-> sum(score) Total score
-> from student s,course c,score sc where s.s_id=sc.s_id and c.c_id=sc.c_id
-> group by s_name with rollup;
+-----------+-------------+-------------+-------------+-------------+-------------+--------+
| full name | Ancient literature | Advanced mathematics | linear algebra | Clinical medicine | Infectious diseases | Total score |
+-----------+-------------+-------------+-------------+-------------+-------------+--------+
| Liu Xiaoqing | 67 | 52 | 55 | 86 | 87 | 347 |
| Liu Yan | 69 | 156 | 173 | 146 | 162 | 706 |
| Liu Ruofei | 65 | 69 | Not elective | Not elective | Not elective | 134 |
| Zhou Jianhua | Not elective | 61 | Not elective | Not elective | 62 | 123 |
| Zhou Huajian | Not elective | 88 | 93 | Not elective | Not elective | 181 |
| Obama | Not elective | 87 | 97 | Not elective | Not elective | 184 |
| Zhang Xueyou | Not elective | 59 | Not elective | Not elective | 48 | 107 |
| Zhang Xiaogang | Not elective | 84 | Not elective | Not elective | 90 | 174 |
| Cao mengde | Not elective | 97 | 68 | 66 | 68 | 299 |
| trump | Not elective | 68 | 86 | Not elective | Not elective | 154 |
| Dong Wenhua | Not elective | 72 | 90 | 90 | 57 | 309 |
| Total score | 201 | 893 | 662 | 388 | 574 | 2718 |
+-----------+--------------+-------------+-------------+-------------+-------------+--------+
12 rows in set (0.03 sec)
3、 ... and 、 Dynamic crosstab
The basic idea of realizing dynamic crosstab is :
(1) Use GROUP_CONCAT The function retrieves all the data in the column to be row column conversion .
(2) Use CONCAT Functions are spliced into the same as static crosstab queries SELECT sentence .
(3) Use pretreatment (prepare) Command execution , Get the final query result .
Still with the above student、course、score Take three tables as an example , Dynamically generate crosstab .
1、 Take out the data in the column to be row column conversion
Use GROUP_CONCAT Function to get the column to be converted into row and column (c_name) Data in .
/* select group_concat(distinct c.c_name) from student s,course c,score sc where s.s_id=sc.s_id and c.c_id=sc.c_id; */
mysql> select group_concat(distinct c.c_name)
-> from student s,course c,score sc where s.s_id=sc.s_id and c.c_id=sc.c_id;
+------------------------------------------------------------------+
| group_concat(distinct c.c_name) |
+------------------------------------------------------------------+
| Clinical medicine , Infectious diseases , Ancient literature , linear algebra , Advanced mathematics |
+------------------------------------------------------------------+
1 row in set (0.00 sec)
2、 Use CONCAT Function to generate a concatenated string
/* explain : by \' For escape characters , Put single quotation marks (') Splice into string SELECT GROUP_CONCAT(DISTINCT (CONCAT('IF(SUM(IF(c_name=\'',c_name,'\',score,0))=0,\' Not elective \',SUM(IF(c_name=\'',c_name,'\',score,0))) ',c_name)) ) INTO @sql_str FROM student s,course c,score sc, (SELECT @sql_str) a where s.s_id=sc.s_id and c.c_id=sc.c_id; */
mysql> SELECT GROUP_CONCAT(DISTINCT
-> (CONCAT('IF(SUM(IF(c_name=\'',c_name,'\',score,0))=0,\' Not elective \',SUM(IF(c_name=\'',c_name,'\',score,0))) ',c_name))
-> )
-> INTO @sql_str
-> FROM student s,course c,score sc, (SELECT @sql_str) a
-> where s.s_id=sc.s_id and c.c_id=sc.c_id;
Query OK, 1 row affected (0.00 sec)
mysql> SELECT @sql_str;
+-----------------------------------------------------------+|
@sql_str
|+----------------------------------------------------------+|
IF(SUM(IF(c_name=' Clinical medicine ',score,0))=0,' Not elective ',SUM(IF(c_name=' Clinical medicine ',score,0))) Clinical medicine ,
IF(SUM(IF(c_name=' Infectious diseases ',score,0))=0,' Not elective ',SUM(IF(c_name=' Infectious diseases ',score,0))) Infectious diseases ,
IF(SUM(IF(c_name=' Ancient literature ',score,0))=0,' Not elective ',SUM(IF(c_name=' Ancient literature ',score,0))) Ancient literature ,
IF(SUM(IF(c_name=' linear algebra ',score,0))=0,' Not elective ',SUM(IF(c_name=' linear algebra ',score,0))) linear algebra ,
IF(SUM(IF(c_name=' Advanced mathematics ',score,0))=0,' Not elective ',SUM(IF(c_name=' Advanced mathematics ',score,0))) Advanced mathematics
|+-------------------------------------------------------------------------+
1 row in set (0.00 sec)
3、 A complete mosaic SELECT sentence
/* SELECT GROUP_CONCAT(DISTINCT (CONCAT('IF(SUM(IF(c_name=\'',c_name,'\',score,0))=0,\' Not elective \',SUM(IF(c_name=\'',c_name,'\',score,0))) ',c_name)) ) INTO @sql_str FROM student s,course c,score sc, (SELECT @sql_str) a where s.s_id=sc.s_id and c.c_id=sc.c_id; set @sql_str = CONCAT('SELECT IFNULL(s_name, \' Total score \') full name ,', @sql_str, ',SUM(score) Total score FROM student s,course c,score sc where s.s_id=sc.s_id and c.c_id=sc.c_id GROUP BY s.s_name WITH ROLLUP;'); */
mysql> SELECT GROUP_CONCAT(DISTINCT
-> (CONCAT('IF(SUM(IF(c_name=\'',c_name,'\',score,0))=0,\' Not elective \',SUM(IF(c_name=\'',c_name,'\',score,0))) ',c_name))
-> )
-> INTO @sql_str
-> FROM student s,course c,score sc, (SELECT @sql_str) a
-> where s.s_id=sc.s_id and c.c_id=sc.c_id;
Query OK, 1 row affected (0.00 sec)
mysql> set @sql_str =
-> CONCAT('SELECT IFNULL(s_name, \' Total score \') full name ,',
-> @sql_str,
-> ',SUM(score) Total score '> FROM student s,course c,score sc
'> where s.s_id=sc.s_id and c.c_id=sc.c_id '> GROUP BY s.s_name WITH ROLLUP;'); Query OK, 0 rows affected (0.00 sec)'
mysql> select @sql_str;
+---------------------------------------------------------------+|
@sql_str
|+-------------------------------------------------------------+|
SELECT
IFNULL(s_name, ' Total score ') full name ,
IF(SUM(IF(c_name=' Clinical medicine ',score,0))=0,' Not elective ',SUM(IF(c_name=' Clinical medicine ',score,0))) Clinical medicine ,
IF(SUM(IF(c_name=' Infectious diseases ',score,0))=0,' Not elective ',SUM(IF(c_name=' Infectious diseases ',score,0))) Infectious diseases ,
IF(SUM(IF(c_name=' Ancient literature ',score,0))=0,' Not elective ',SUM(IF(c_name=' Ancient literature ',score,0))) Ancient literature ,
IF(SUM(IF(c_name=' linear algebra ',score,0))=0,' Not elective ',SUM(IF(c_name=' linear algebra ',score,0))) linear algebra ,
IF(SUM(IF(c_name=' Advanced mathematics ',score,0))=0,' Not elective ',SUM(IF(c_name=' Advanced mathematics ',score,0))) Advanced mathematics ,
SUM(score) Total score
FROM student s,course c,score sc
where s.s_id=sc.s_id and c.c_id=sc.c_id
GROUP BY s.s_name WITH ROLLUP;
+---------------------------------------------------------------------------+
1 row in set (0.00 sec)
4、 Use the preprocessing command to execute the spliced string
/* -- PREPARE Statement syntax description : PREPARE statement_name FROM SQL character string ; -- Execute preprocessing statements EXECUTE statement_name; -- Delete the preprocessing statement definition DEALLOCATE | DROP PREPARE statement_name; */
mysql> PREPARE stmt from @sql_str;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt;
+-----------+-------------+-------------+-------------+--------------+-------------+--------+
| full name | Clinical medicine | Infectious diseases | Ancient literature | linear algebra | Advanced mathematics | Total score |
+-----------+-------------+-------------+-------------+--------------+-------------+--------+
| Liu Xiaoqing | 86 | 87 | 67 | 55 | 52 | 347 |
| Liu Yan | 146 | 162 | 69 | 173 | 156 | 706 |
| Liu Ruofei | Not elective | Not elective | 65 | Not elective | 69 | 134 |
| Zhou Jianhua | Not elective | 62 | Not elective | Not elective | 61 | 123 |
| Zhou Huajian | Not elective | Not elective | Not elective | 93 | 88 | 181 |
| Obama | Not elective | Not elective | Not elective | 97 | 87 | 184 |
| Zhang Xueyou | Not elective | 48 | Not elective | Not elective | 59 | 107 |
| Zhang Xiaogang | Not elective | 90 | Not elective | Not elective | 84 | 174 |
| Cao mengde | 66 | 68 | Not elective | 68 | 97 | 299 |
| trump | Not elective | Not elective | Not elective | 86 | 68 | 154 |
| Dong Wenhua | 90 | 57 | Not elective | 90 | 72 | 309 |
| Total score | 388 | 574 | 201 | 662 | 893 | 2718 |
+-----------+-------------+--------------+-------------+--------------+-------------+--------+
12 rows in set (0.00 sec)
mysql> DEALLOCATE prepare stmt;
Query OK, 0 rows affected (0.00 sec)
5、 Define the crosstab query as a stored procedure
Define the above code as a stored procedure stored in the database , Call repeatedly .
The code is as follows :
DELIMITER &&
CREATE PROCEDURE sp_crosstable() reads SQL data
BEGIN
SET @sql_str = NULL;
SELECT GROUP_CONCAT(DISTINCT
(CONCAT('IF(SUM(IF(c_name=\'',c_name,'\',score,0))=0,\' Not elective \',SUM(IF(c_name=\'',c_name,'\',score,0))) ',c_name))
)
INTO @sql_str
FROM student s,course c,score sc, (SELECT @sql_str) a
where s.s_id=sc.s_id and c.c_id=sc.c_id;
set @sql_str =
CONCAT('SELECT IFNULL(s_name, \' Total score \') full name ,',
@sql_str,
',SUM(score) Total score FROM student s,course c,score sc where s.s_id=sc.s_id and c.c_id=sc.c_id GROUP BY s.s_name WITH ROLLUP;');
PREPARE stmt from @sql_str;
EXECUTE stmt;
DEALLOCATE prepare stmt;
END &&
DELIMITER ;
Execute the above code , Generate stored procedure :
mysql> DELIMITER &&
mysql> CREATE PROCEDURE sp_crosstable() reads SQL data
-> BEGIN
-> SET @sql_str = NULL;
->
-> SELECT GROUP_CONCAT(DISTINCT
-> (CONCAT('IF(SUM(IF(c_name=\'',c_name,'\',score,0))=0,\' Not elective \',SUM(IF(c_name=\'',c_name,'\',score,0))) ',c_name))
-> )
-> INTO @sql_str
-> FROM student s,course c,score sc, (SELECT @sql_str) a
-> where s.s_id=sc.s_id and c.c_id=sc.c_id;
->
-> set @sql_str =
-> CONCAT('SELECT IFNULL(s_name, \' Total score \') full name ,',
-> @sql_str,
-> ',SUM(score) Total score '> FROM student s,course c,score sc
'> where s.s_id=sc.s_id and c.c_id=sc.c_id '> GROUP BY s.s_name WITH ROLLUP;'); -> -> PREPARE stmt from @sql_str; -> EXECUTE stmt; -> DEALLOCATE prepare stmt; -> END && Query OK, 0 rows affected (0.10 sec) mysql> DELIMITER ; mysql> select name from mysql.proc where db='mydb';
+---------------+
| name |
+---------------+
| sp_crosstable |
+---------------+
1 row in set (0.01 sec)
Execute stored procedures , Generate crosstab :
mysql> CALL sp_crosstable;
+-----------+--------------+--------------+--------------+--------------+--------------+--------+
| full name | Clinical medicine | Infectious diseases | Ancient literature | linear algebra | Advanced mathematics | Total score |
+-----------+--------------+--------------+--------------+--------------+--------------+--------+
| Liu Xiaoqing | 86 | 87 | 67 | 55 | 52 | 347 |
| Liu Yan | 146 | 162 | 69 | 173 | 156 | 706 |
| Liu Ruofei | Not elective | Not elective | 65 | Not elective | 69 | 134 |
| Zhou Jianhua | Not elective | 62 | Not elective | Not elective | 61 | 123 |
| Zhou Huajian | Not elective | Not elective | Not elective | 93 | 88 | 181 |
| Obama | Not elective | Not elective | Not elective | 97 | 87 | 184 |
| Zhang Xueyou | Not elective | 48 | Not elective | Not elective | 59 | 107 |
| Zhang Xiaogang | Not elective | 90 | Not elective | Not elective | 84 | 174 |
| Cao mengde | 66 | 68 | Not elective | 68 | 97 | 299 |
| trump | Not elective | Not elective | Not elective | 86 | 68 | 154 |
| Dong Wenhua | 90 | 57 | Not elective | 90 | 72 | 309 |
| Total score | 388 | 574 | 201 | 662 | 893 | 2718 |
+-----------+--------------+--------------+--------------+--------------+--------------+--------+
12 rows in set (0.03 sec)
Query OK, 0 rows affected (0.03 sec)
边栏推荐
- The high-quality digital collection of guochuang's "children's song line" is on sale, and you are invited to create a young martial arts Jianghu dream
- MySQL table field quantity limit and row size limit
- 【电赛训练】非接触物体尺寸形态测量 2020年电赛G题
- Tutorial on principles and applications of database system (041) -- MySQL query (III): setting query conditions
- Introduction to QT (2.1 the first procedure for the beginning of QT)
- Classic examples of C language - use 4 × The matrix displays all integers from 1 to 16 and calculates the sum of each row, column, and diagonal
- 網絡系統實驗:ping不通的問題解决
- 采坑websocket總結
- [QNX Hypervisor 2.2用户手册]9 VM配置参考
- Résumé du websocket minier
猜你喜欢

项目场景:nvidia-smi Unable to datemine the device handle for GPU 0000:01:00.0: Unknow Error

Testers who have been employed for 3 months are facing employment confirmation. Leaders: 1 year of work experience is packaged into 5 years, and the probation period is eliminated

MySQL exercise: all employees reporting to the CEO

Customize an object

Interviewer: if the order is not paid within 30 minutes after it is generated, it will be automatically cancelled. How to realize it?

QT入门篇(2.1初入QT的开始第一个程序)

Development of main applet for business card traffic near the map
CA digital certificate

Difference between data index and label system of data warehouse
![[video game training] non contact object size and shape measurement 2020 video game G](/img/b7/d70a702e52062e38176b589eb15415.jpg)
[video game training] non contact object size and shape measurement 2020 video game G
随机推荐
Notes and Reflections on the red dust of the sky (V) strong culture and weak culture
暑假第四周总结
《天幕红尘》笔记与思考(五)强势文化与弱势文化
C language book recommendation
Comparison of the shortcomings of redis master-slave, sentinel and cluster architectures
落枕如何快速缓解
Image processing: Generation 3 × Window of 3
SAP 电商云 Spartacus UI Store 相关的设计明细
Network system experiment: solve the problem of Ping failure
MySQL's heart index
High number_ Chapter 1 space analytic geometry and vector algebra__ Two point distance
Redis persistence mechanism RDB, AOF
C language: deep analysis of const keyword
This is a big problem
AWS Part 4 one machine and one secret
Bean Validation使用篇----05
The prediction of domestic AI protein structure reproduced a breakthrough and solved the 3D structure with a single sequence. Peng Jian's team: "the last piece of puzzle since alphafold2 has been comp
How to improve data quality
网络系统实验:ping不通的问题解决
The most basic code interpretation of C language