SQL column-to-row

Source: Internet
Author: User
Tags crosstab

Create table [Test] (

[Id] [int] IDENTITY (1, 1) not null,

[Name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL,

[Subject] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL,

[Source] [numeric] (18, 0) NULL

) ON [PRIMARY]

GO

Insert into [test] ([name], [subject], [Source]) values (N 'zhang san', N '', 60)

Insert into [test] ([name], [subject], [Source]) values (N 'Li si', N 'mat', 70)

Insert into [test] ([name], [subject], [Source]) values (N 'wang wu', n' ', 80)

Insert into [test] ([name], [subject], [Source]) values (N 'wang wu', N 'mat', 75)

Insert into [test] ([name], [subject], [Source]) values (N 'wang wu', n' ', 57)

Insert into [test] ([name], [subject], [Source]) values (n'li si', n' ', 80)

Insert into [test] ([name], [subject], [Source]) values (N 'zhang san', N 'angles', 100)

Go

-- Implementation of cross tabulation statements:

-- Used: the number of columns in the crosstab chart is determined.

Select name, sum (case subject when 'mate' then source else 0 end) as 'mate ',

Sum (case subject when 'then source else 0 end) as 'hangzhou ',

Sum (case subject when 'chine' then source else 0 end) as 'chine'

From test

Group by name

-- Used: the number of columns in the crosstab chart is uncertain.

Declare @ SQL varchar (8000)

Set @ SQL = 'select name ,'

Select @ SQL = @ SQL + 'sum (case subject when ''' + subject + '''

Then source else 0 end) as ''' + subject + ''','

From (select distinct subject from test) as

Select @ SQL = left (@ SQL, len (@ SQL)-1) + 'from test group by name'

Exec (@ SQL)

Go

-- Used: the number of columns in the crosstab chart is uncertain.

Declare @ SQL varchar (8000)

Set @ SQL = 'select id ,'

Select @ SQL = @ SQL + '(case subject when ''' + subject + '''

Then source else null end) as ''' + subject + ''','

From (select distinct subject from test) as

Select @ SQL = left (@ SQL, len (@ SQL)-1) + 'from Test'

Exec (@ SQL)

Go

Related Article

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.