Horizontal table, longitudinal table conversion

Source: Internet
Author: User

1. Vertical table converted to horizontal table

Columnar SQL

CREATE TABLE [dbo].[TableA](    [Name] [nvarchar](Ten) not NULL,    [Course] [nvarchar]( -) not NULL,    [Grade] [int]  not NULL)INSERT [dbo].[TableA]([Name],[Course],[Grade])VALUES(N'Zhang San'+ I'language', the)INSERT [dbo].[TableA]([Name],[Course],[Grade])VALUES(N'Zhang San'N'Mathematics', the)INSERT [dbo].[TableA]([Name],[Course],[Grade])VALUES(N'Zhang San'N'English', -)INSERT [dbo].[TableA]([Name],[Course],[Grade])VALUES(N'John Doe'N'language', the)INSERT [dbo].[TableA]([Name],[Course],[Grade])VALUES(N'John Doe'N'Mathematics', -)

Convert SQL

SelectName,SUM( CaseCourse when 'language'  ThenGradeElse 0 End) aslanguages,SUM( CaseCourse when 'Mathematics'  ThenGradeElse 0 End) asMathematics,SUM( CaseCourse when 'English'  ThenGradeElse 0 End) asEnglish fromTableAGroup  byName

Conversion results

2. Horizontal table converted to vertical table

Horizontal Table SQL

Create TableTable_b (IDint Identity(1,1)Primary Key, namevarchar( -), Languageint, Mathematicsint, Englishint)Insert  intoTable_b (name, language, maths, English)Values('Zhang San', -, -, the)Insert  intoTable_b (name, language, maths, English)Values('John Doe', -, -, $)Insert  intoTable_b (name, language, maths, English)Values('Harry', the, -,Panax Notoginseng)

Convert SQL

Selectname,'language'  assubjects, Languages asAchievements fromTable_bUnion  AllSelectname,'Mathematics'  asSubjects, Mathematics asAchievements fromTable_bUnion  AllSelectname,'English'  assubjects, English asAchievements fromTable_bOrder  byName, subject

Conversion results

Horizontal table, longitudinal table conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.