English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Methods to Convert Vertical and Horizontal Tables in SQL Server

1converted to horizontal table

Table_A: Vertical Table Structure

The structure after conversion:

SQL example for converting vertical tables to horizontal tables:

SELECT Name ,
SUM(CASE WHEN Course = N'语文' THEN Grade
ELSE 0
END) AS Chinese ,
SUM(CASE WHEN Course = N'数学' THEN Grade
ELSE 0
END) AS Mathematics ,
SUM(CASE WHEN Course = N'英语' THEN Grade
ELSE 0
END) AS English
FROM dbo.Table_A
GROUP BY Name

2, horizontal table to vertical table

The structure of the horizontal table Table_B:

The table structure after conversion:

SQL example for converting horizontal tables to vertical tables:

SELECT Name ,
'Chinese' AS Course ,
Chinese AS Score
FROM dbo.Table_B
UNION ALL
SELECT Name ,
'Mathematics' AS Course ,
Mathematics AS Score
FROM dbo.Table_B
UNION ALL
SELECT Name ,
'English' AS Course ,
English AS Score
FROM dbo.Table_B
ORDER BY Name ,
Course DESC 

 The above-mentioned is the implementation method of converting vertical tables and horizontal tables in SQL Server introduced by the editor for everyone. I hope it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time. At the same time, I would also like to express my heartfelt thanks to everyone for their support of the Yelling Tutorial website!

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like