How to realize row-to-column transfer in sql statement
This article will explain in detail how to achieve row conversion in sql statements. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
Preface
Generally, rows and columns are used when doing data statistics. If you want to count the students' scores, what will be queried in the database will be like this, but this will not achieve the desired effect, so you should deal with it when you query. I won't say much about the following words. Let's take a look at the detailed introduction.
CREATE TABLE TestTable ([Id] [int] IDENTITY (1jue 1) NOT NULL, [UserName] [nvarchar] (50) NULL, [Subject] [nvarchar] (50) NULL, [Source] [numeric] (18,0) NULL) ON [PRIMARY] goINSERT INTO TestTable ([UserName], [Subject], [Source]) SELECT N 'Zhang San', N 'Chinese', 60 UNION ALL SELECT N'Li Si', N 'Mathematics', 70 UNION ALL SELECT N 'Wang Wu', N' English' 80 UNION ALL SELECT N 'Wang Wu', N 'Mathematics', 75 UNION ALL SELECT N 'Wang Wu', N 'Chinese', 57 UNION ALL SELECT N'Li Si', N 'Chinese', 80 UNION ALL SELECT N 'Zhang San', N 'English', 100GO
Here I use three methods to implement row transfer. The first one is static row transfer.
Select UserName name, sum (case Subject when 'language' then Source else 0 end) Chinese, sum (case Subject when 'Mathematics' then Source else 0 end) Mathematics, sum (case Subject when 'English' then Source else 0 end) English from TestTable group by UserName
Use povit rows to transfer columns
Select * from (select UserName,Subject,Source from TestTable) testpivot (sum (Source) for Subject in (Chinese, Mathematics, English)) pvt
Use stored procedures to transfer rows to columns
Alter proc pro_test@userImages varchar, @ Subject varchar, @ Subject1 varchar, @ TableName varchar (50) as declare @ sql varchar (max) = 'select * from (select' + @ userImages+' from'+@TableName+') tabpivot (sum ('+ @ Subject+') for Subject ('+ @ Subject1+')) pvt'exec (@ sql) goexec pro_test 'UserName,Subject,Source','TestTable','Subject',' Chinese, Mathematics, English'
This is how they all work.
The above three ways to achieve row conversion, we can adopt different methods according to our own needs.
This is the end of this article on "how to realize row conversion in sql statements". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.