当前位置:网站首页>5 minutes to understand MySQL row column conversion
5 minutes to understand MySQL row column conversion
2022-04-23 05:07:00 【hi wei】
Partners want to find out exactly what they want to see MySQL article ? here → MySQL Column catalog | Click here
MySQL
Transfer line column, For students who often process data , It must be no stranger , Even impressive , Because it probably bothers you , Let you be stunned ~ But when you see this article , This problem is no longer a problem , Timely collection , Who will ask you this question later , Just throw it in his face , Paste and use .
Here's a little secret , Actually, me and 《 Little joy 》 Are you classmates or good friends ~~ Today, I'll take some of our brother's college entrance examination scores as the test table . Um. , Believe it, brothers ? I also have a group photo of us at school , I haven't been in senior three yet PS, So the picture must be true !

I don't say much nonsense , First , Let's take a look at our Test table data and Expected query results .
mysql> SELECT * FROM t_gaokao_score;
+----+--------------+--------------+-------+
| id | student_name | subject | score |
+----+--------------+--------------+-------+
| 1 | Lin Leier | Chinese language and literature | 148 |
| 2 | Lin Leier | mathematics | 150 |
| 3 | Lin Leier | English | 147 |
| 4 | Joe yingzi | Chinese language and literature | 121 |
| 5 | Joe yingzi | mathematics | 106 |
| 6 | Joe yingzi | English | 146 |
| 7 | Fang Yifan | Chinese language and literature | 70 |
| 8 | Fang Yifan | mathematics | 90 |
| 9 | Fang Yifan | English | 59 |
| 10 | Fang Yifan | Extra points for Specialty | 200 |
| 11 | Chen ha ha | Chinese language and literature | 109 |
| 12 | Chen ha ha | mathematics | 92 |
| 13 | Chen ha ha | English | 80 |
+----+--------------+--------------+-------+
13 rows in set (0.00 sec)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
Look at us. Transfer line column Results after conversion :
+--------------+--------+--------+--------+--------------+
| student_name | Chinese language and literature | mathematics | English | Extra points for Specialty |
+--------------+--------+--------+--------+--------------+
| Lin Leier | 148 | 150 | 147 | 0 |
| Joe yingzi | 121 | 106 | 146 | 0 |
| Fang Yifan | 70 | 90 | 59 | 200 |
| Chen ha ha | 109 | 92 | 80 | 0 |
+--------------+--------+--------+--------+--------------+
4 rows in set (0.00 sec)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
good , Let's take a look SQL How it was written , by the way , Creating table structure and importing test data SQL Put it at the end of the article , Self taking ~
A plane ticket
One 、 Transfer line column SQL How to write it
- Method 1 、 Use
case..when..thenConduct Transfer line column
SELECT student_name,
SUM(CASE `subject` WHEN ' Chinese language and literature ' THEN score ELSE 0 END) as ' Chinese language and literature ',
SUM(CASE `subject` WHEN ' mathematics ' THEN score ELSE 0 END) as ' mathematics ',
SUM(CASE `subject` WHEN ' English ' THEN score ELSE 0 END) as ' English ',
SUM(CASE `subject` WHEN ' Extra points for Specialty ' THEN score ELSE 0 END) as ' Extra points for Specialty '
FROM t_gaokao_score
GROUP BY student_name;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
If not used here SUM() Will be submitted to the
sql_mode=only_full_group_byRelated errors , needAggregate functions and group by Continuous useorUse distinctTo solve the problem .
Actually , addedSUM()To be able to use GROUP BY according to student_name Grouping , every last student_name Correspondingsubject=" Chinese language and literature "After all, there is only one record , therefore SUM() The value of is equal to that of the corresponding record score Value . Of course , It can also be replaced byMAX().

- Method 2 、 Use
IF()Conduct Transfer line column :
SELECT student_name,
SUM(IF(`subject`=' Chinese language and literature ',score,0)) as ' Chinese language and literature ',
SUM(IF(`subject`=' mathematics ',score,0)) as ' mathematics ',
SUM(IF(`subject`=' English ',score,0)) as ' English ',
SUM(IF(`subject`=' Extra points for Specialty ',score,0)) as ' Extra points for Specialty '
FROM t_gaokao_score
GROUP BY student_name;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
This method will IF(subject=' Chinese language and literature ',score,0) As a condition , adopt student_name Grouping , All after grouping subject=' Chinese language and literature ’ The record of score The fields go SUM() operation , If score If there is no value, the default value is 0.
This way and case..when..then The principle of the method is the same , More concise than , It is recommended to use .
Two 、 If leadership @ you , Let you add the total sequence to the result set ?
Friendship tips: When we deal with row to column data in our work , Try to count the total 、 Average, etc. plus , Convenient for leaders to consult , Save him circulation BB you .
Words , Do you remember what the grade sheet was like at school ? Do you usually look from top to bottom or from bottom to top ?Voting at the end of the text , Come and have fun for everyone !
How to write it : utilize SUM(IF()) Generate columns ,WITH ROLLUP Generate summary columns and rows , And make use of IFNULL Display the total line title as total
SELECT IFNULL(student_name,' total ') AS student_name,
SUM(IF(`subject`=' Chinese language and literature ',score,0)) AS ' Chinese language and literature ',
SUM(IF(`subject`=' mathematics ',score,0)) AS ' mathematics ',
SUM(IF(`subject`=' English ',score,0)) AS ' English ',
SUM(IF(`subject`=' Extra points for Specialty ',score,0)) AS ' Extra points for Specialty ',
SUM(score) AS ' total '
FROM t_gaokao_score
GROUP BY student_name WITH ROLLUP;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Query results :
+--------------+--------+--------+--------+--------------+--------+
| student_name | Chinese language and literature | mathematics | English | Extra points for Specialty | total |
+--------------+--------+--------+--------+--------------+--------+
| Joe yingzi | 121 | 106 | 146 | 0 | 373 |
| Fang Yifan | 70 | 90 | 59 | 200 | 419 |
| Lin Leier | 148 | 150 | 147 | 0 | 445 |
| Chen ha ha | 113 | 116 | 80 | 0 | 309 |
| total | 452 | 462 | 432 | 200 | 1546 |
+--------------+--------+--------+--------+--------------+--------+
5 rows in set, 1 warning (0.00 sec)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
3、 ... and 、 Once again, the leadership is double. @ You need to change
Let you convert the score into specific content display ( good 、 good 、 Ordinary 、 Bad ),430 Key universities with scores above ,400 Score more than one book ,350 Two or more copies ,350 Move bricks below , How to write ?
It's disgusting , Don't say the , Xiangan rice ~~( A unique skill : Fan Dun )
Here we need case when nesting There you go , Look at the tall , It's just ordinary nesting . Find out the scores of each subject after grouping on the first floor , Replace it with grade on the second floor .
SELECT student_name,
MAX(
CASE subject
WHEN ' Chinese language and literature ' THEN
(
CASE
WHEN score - (select avg(score) from t_gaokao_score where subject=' Chinese language and literature ') > 20 THEN
' good '
WHEN score - (select avg(score) from t_gaokao_score where subject=' Chinese language and literature ') > 10 THEN
' good '
WHEN score - (select avg(score) from t_gaokao_score where subject=' Chinese language and literature ') >= 0 THEN
' Ordinary '
ELSE
' Bad '
END
)
END
) as ' Chinese language and literature ',
MAX(
CASE subject
WHEN ' mathematics ' THEN
(
CASE
WHEN score - (select avg(score) from t_gaokao_score where subject=' mathematics ') > 20 THEN
' good '
WHEN score - (select avg(score) from t_gaokao_score where subject=' mathematics ') > 10 THEN
' good '
WHEN score - (select avg(score) from t_gaokao_score where subject=' mathematics ') >= 0 THEN
' Ordinary '
ELSE
' Bad '
END
)
END
) as ' mathematics ',
MAX(
CASE subject
WHEN ' English ' THEN
(
CASE
WHEN score - (select avg(score) from t_gaokao_score where subject=' English ') > 20 THEN
' good '
WHEN score - (select avg(score) from t_gaokao_score where subject=' English ') > 10 THEN
' good '
WHEN score - (select avg(score) from t_gaokao_score where subject=' English ') >= 0 THEN
' Ordinary '
ELSE
' Bad '
END
)
END
) as ' English ',
SUM(score) as ' Total score ',
(CASE WHEN SUM(score) > 430 THEN ' Key universities '
WHEN SUM(score) > 400 THEN ' a copy '
WHEN SUM(score) > 350 THEN ' Two copies '
ELSE ' Move bricks at the construction site '
END ) as ' result '
FROM t_gaokao_score
GROUP BY student_name
ORDER BY SUM(score) desc;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
Let's take a look at the output :
+--------------+--------+--------+--------+--------+--------------+
| student_name | Chinese language and literature | mathematics | English | Total score | result |
+--------------+--------+--------+--------+--------+--------------+
| Lin Leier | good | good | good | 445 | Key universities |
| Fang Yifan | Bad | Bad | Bad | 419 | a copy |
| Joe yingzi | Ordinary | Bad | good | 373 | Two copies |
| Chen ha ha | Ordinary | Ordinary | Bad | 309 | Move bricks at the construction site |
+--------------+--------+--------+--------+--------+--------------+
4 rows in set (0.00 sec)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
From people's experience , Honest children suffer the most , I knew I'd go to art and sports ~
Four 、 Conclusion
Okay ,SQL These are the above contents , Questions can be written in the comments area , Ha Ge will reply you when fishing ~~`
Help three times , finger heart ღ( ´・ᴗ・` )

appendix : Create a table structure & Test data SQL
Table structure :
DROP TABLE IF EXISTS `t_gaokao_score`;
CREATE TABLE `t_gaokao_score` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`student_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' The student's name ',
`subject` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' subject ',
`score` double NULL DEFAULT NULL COMMENT ' achievement ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Import test data
INSERT INTO `t_gaokao_score` VALUES
(1, ' Lin Leier ', ' Chinese language and literature ', 148),
(2, ' Lin Leier ', ' mathematics ', 150),
(3, ' Lin Leier ', ' English ', 147),
(4, ' Joe yingzi ', ' Chinese language and literature ', 121),
(5, ' Joe yingzi ', ' mathematics ', 106),
(6, ' Joe yingzi ', ' English ', 146),
(7, ' Fang Yifan ', ' Chinese language and literature ', 70),
(8, ' Fang Yifan ', ' mathematics ', 90),
(9, ' Fang Yifan ', ' English ', 59),
(10, ' Fang Yifan ', ' Extra points for Specialty ', 200),
(11, ' Chen ha ha ', ' Chinese language and literature ', 109),
(12, ' Chen ha ha ', ' mathematics ', 92),
(13, ' Chen ha ha ', ' English ', 80);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
版权声明
本文为[hi wei]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220550379237.html
边栏推荐
- Repair of self calibration SPC failure of Tektronix oscilloscope dpo3054
- [WinUI3]编写一个仿Explorer文件管理器
- Innovation training (XII) reptile
- 用LCR表完美测试无线充电系统中的线圈
- MySQL memo (for your own query)
- 使用zerotier让异地设备组局域网
- Various ways of writing timed tasks of small programs
- Innovation training (10)
- Get the number of days between dates, get the Chinese date, get the date of the next Monday of the date, get the working day, get the rest day
- What are instruction cycles, machine cycles, and clock cycles?
猜你喜欢

跨境电商 | Facebook 和 Instagram:哪个社交媒体更适合你?
![View, modify and delete [database] table](/img/a2/fcb38f2006772a1ec45cab520620ba.png)
View, modify and delete [database] table

JS engine loop mechanism: synchronous, asynchronous, event loop

Live delivery form template - automatically display pictures - automatically associate series products

【数据库】MySQL基本操作(基操~)
![[WinUI3]編寫一個仿Explorer文件管理器](/img/3e/62794f1939da7f36f7a4e9dbf0aa7a.png)
[WinUI3]編寫一個仿Explorer文件管理器

Leetcode 1547: minimum cost of cutting sticks
![[2021] Spatio-Temporal Graph Contrastive Learning](/img/7d/67a0bfa0adecee24bbe291a25ae906.png)
[2021] Spatio-Temporal Graph Contrastive Learning

多线程基本概念(并发与并行、线程与进程)和入门案例

【数据库】表的查看、修改和删除
随机推荐
Independent station operation | Facebook marketing artifact - chat robot manychat
Docker installation and mysql5 7 installation
Wine (COM) - basic concept
Progress of innovation training (III)
Backup MySQL database with Navicat
[database] MySQL basic operation (basic operation ~)
Solve valueerror: argument must be a deny tensor: 0 - got shape [198602], but wanted [198602, 16]
Summary of R & D technology
Leetcode -- heuristic search
Use AES encryption - reuse the wisdom of predecessors
configmap
Informatics Aosai yibentong 1212: letters | openjudge 2.5 156: Letters
Innovation training (II) task division
Innovation training (XI) airline ticket crawling company information
Chapter I overall project management of information system project manager summary
Mac enters MySQL terminal command
Learning Android II from scratch - activity
mysql5. 7. X data authorization leads to 1141
Using MySQL with Oracle
AQS源码阅读