当前位置:网站首页>MySQL row to column, column to row, multiple columns to one row, one row to multiple columns
MySQL row to column, column to row, multiple columns to one row, one row to multiple columns
2022-06-12 22:59:00 【Witty flowers】
This blog is about the interview I saw before SQL topic Used it to learn After reading this blog , I believe you will be right SQL Grammar has different feelings and understandings .
Version Description
mysql8.0
One 、 Transfer line column
demand

classic case when Realization
select
name,
max(case subject when ' Chinese language and literature ' then resuilt else 0 end) ' Chinese language and literature ',
max(case subject when ' mathematics ' then resuilt else 0 end) ' mathematics ',
max(case subject when ' Physics ' then resuilt else 0 end) ' Physics '
from student group by name

Use if sentence
Similar in general case when
select name,
max(if(subject = ' Chinese language and literature ',resuilt,0)) ' Chinese language and literature '
from student group by name

Dynamic splicing sql sentence , No matter how many rows are transferred
set @sql = null;
select group_concat(distinct concat('max(if(a.subject = ''',a.subject,''', a.resuilt, 0)) as ''',a.subject, '''')) into @sql from student a;
set @sql = concat('select name,', @sql, 'from student a group by a.name' );
prepare stmt from @sql; -- Dynamically generate scripts , Prepare a statement
execute stmt; -- Executing scripts dynamically , Execute the prepared statement
deallocate prepare stmt; -- Release prepared statements

Extended analysis
mysql Why do I have to use sum perhaps max
In case of this problem, we can debug sql, To solve our doubts .
Two 、 Column turned
demand
take

Convert to

select
name,
' Chinese language and literature ' as subject,
chinese as resuilt
from -- Note that the normal here should be from Directly followed by a table Lazy don't want to create a table structure Direct subquery ( Row to column code )
(select
name,
max(case subject when ' Chinese language and literature ' then resuilt else 0 end) 'chinese',
max(case subject when ' mathematics ' then resuilt else 0 end) 'math',
max(case subject when ' Physics ' then resuilt else 0 end) 'physics'
from student group by name
) t
union all
select
name,
' mathematics ' as subject,
math as resuilt
from -- Note that the normal here should be from Directly followed by a table Lazy don't want to create a table structure Direct subquery ( Row to column code )
(select
name,
max(case subject when ' Chinese language and literature ' then resuilt else 0 end) 'chinese',
max(case subject when ' mathematics ' then resuilt else 0 end) 'math',
max(case subject when ' Physics ' then resuilt else 0 end) 'physics'
from student group by name
) t
union all
select
name,
' Physics ' as subject,
physics as resuilt
from -- Note that the normal here should be from Directly followed by a table Lazy don't want to create a table structure Direct subquery ( Row to column code )
(select
name,
max(case subject when ' Chinese language and literature ' then resuilt else 0 end) 'chinese',
max(case subject when ' mathematics ' then resuilt else 0 end) 'math',
max(case subject when ' Physics ' then resuilt else 0 end) 'physics'
from student group by name
) t

summary
Transfer line column , Use case…when Query data by situation ,group by and sum/max Screening
Column turned , Use... For each column of data required for query union perhaps union all Union
3、 ... and 、 Multiple columns to one row
demand
take

Turn into

select name,GROUP_CONCAT(`subject`,':',resuilt) ' achievement ' from student group by name

GROUP_CONCAT(expr) This function combines the non empty column values according to the grouping conditions and finally returns . If there is a null value , Then return to empty
Four 、 One row to many columns
demand
take

Turn into

a surface
select
name,
marks,
case
when locate(' Chinese language and literature ',marks) > 0 then substring_index(substring_index(marks,' Chinese language and literature :',-1),',',1) else 0 end
as Chinese language and literature ,
case
when locate(' mathematics ',marks) > 0 then substring_index(substring_index(marks,' mathematics :',-1),',',1) else 0 end
as mathematics ,
case
when locate(' Physics ',marks) > 0 then substring_index(substring_index(marks,' Physics :',-1),',',1) else 0 end
as Physics ,
case
when locate(' history ',marks) > 0 then substring_index(substring_index(marks,' history :',-1),',',1) else 0 end
as history
from
(select
name,
GROUP_CONCAT(subject,':',resuilt) marks
from
student group by name) a
It's just the first step give an example The request is still one step away Use union all Continue processing sql
b surface
select
name,
' Chinese language and literature ' subject,
Chinese language and literature score
from
(a surface ) b
union all
select
name,
' mathematics ' subject,
mathematics score
from
(a surface ) b
union all
select
name,
' Physics ' subject,
Physics score
from
(a surface ) b
union all
select
name,
' history ' subject,
history score
from
(a surface ) b

Locate The main function is to determine whether a string contains another string , Such as
Locate(str,sub) > 0, Express sub The string contains str character string ;
Locate(str,sub) = 0, Express sub String does not contain str character string .
substring_index( Parameters str, Parameters delim, Parameters count)
str : What to deal with character string
delim: Separator
count: Count
in other words , If count Positive number , So it's counting from left to right , The first N All of the contents to the left of the separator ! contrary , If it's a negative number , So it's counting from the right , The first N Everything to the right of the separator ,
Reference article
elementary analysis MySQL in concat as well as group_concat Use - Programmer base
MySQL function Locate Use _ Blog without wind or rain tonight -CSDN Blog _mysql Of locate
边栏推荐
- iShot
- [Part 8] semaphore source code analysis and application details [key points]
- The shutter library recommends sizer to help you easily create a responsive UI
- The programmer dedicated to promoting VIM has left. Father of vim: I will dedicate version 9.0 to him
- ASP. Net core Middleware
- 四元数简介
- JVM foundation - > what is STW?
- 人脸检测:MTCNN
- Inventory of CV neural network models from 2021 to 2022
- DETR(Detection with Transformers) 学习笔记
猜你喜欢

ShardingSphere-proxy-5.0.0部署之分表实现(一)

Qrcodejs2 QR code generation JS

Alcohol detector based on 51 single chip microcomputer

MYSQL 行转列、列转行、多列转一行、一行转多列

The annual salary of 500000 is one line, and the annual salary of 1million is another line

JVM foundation > CMS garbage collector
![LeetCode 890 查找和替换模式[map] HERODING的LeetCode之路](/img/a2/186439a6d50339ca7f299a46633345.png)
LeetCode 890 查找和替换模式[map] HERODING的LeetCode之路

C # reading table data in word

JVM Basics - > how to troubleshoot JVM problems in your project

2022 heavyweight: growth law - skillfully use digital marketing to break through enterprise difficulties
随机推荐
Introduction to Quaternion
Flutter series part: detailed explanation of GridView layout commonly used in flutter
China embolic coil market trend report, technical innovation and market forecast
C # reading table data in word
Web3 principle and decentralization
VIM use the lower right 4 keys
Pytorch中的梯度累加【在实验时,由于GPU显存限制,遇到batch_size不能再增大的情况。为解决该问题,使用梯度累加方法】
【LeetCode】300.最长上升子序列
认识的几位清华同学都离职了……
Colab tutorial (super detailed version) and colab pro/colab pro+ usage evaluation
Design of traceid in the project
【LeetCode】69. Square root of X
【LeetCode】53. Maximum subarray and
QT quick 3D learning: use mouse and keyboard to control node position and direction
四元数简介
[web technology] 1348- talk about several ways to implement watermarking
Su embedded training day13 - file IO
lua 循环语句
[Part 8] semaphore source code analysis and application details [key points]
認識的幾比特清華同學都離職了……