Use Dynamic statements to change a typical column to a row.

Source: Internet
Author: User

-- Test Data

Declare @ tab table (ID varchar (3), Class varchar (10), sums INT)

Insert @ Tab
Select '001', 'computer ', '65' Union all

Select '002 ', 'computer', '75' Union all
Select '001', 'artbe', '77 'Union all

Select '003 ', 'sport', '54' Union all
Select '004 ', 'artbe', '65' Union all

Select '005 ', 'sport', '55' Union all
Select '001', 'sport', '56' Union all

Select '002 ', 'Sports', '88 'Union all
Select '002 ', 'artbe', '98' Union all

Select '003 ', 'computer', '82 'Union all
Select '003 ', 'artbe', '92' Union all

Select '004 ', 'computer', '85 'Union all
Select '004 ', 'sport', '25' Union all

Select '005 ', 'computer', '89 'Union all
Select '005 ', 'artbe', '99 ';

-- Select * From @ Tab

-- Below is the testCode

Select * into # temp1 from @ Tab
Declare @ STR varchar (8000)

Set @ STR = 'select ID as number ,'
Select @ STR = @ STR +'

Sum (case class when ''' + class + ''' then sums else 0 end) as ''' + class + 'score '+ ''','

From (select distinct class from # temp1) T

Set @ STR = left (@ STR, Len (@ Str)-1) + 'from # temp1 group by id'
Exec (@ Str)

Drop table # temp1

/* The following is the test result.

(15 rows are affected)

(15 rows are affected)

Number, computer score, art score, sports score

-------------------------------------
001 65 77 56
002 75 98 88

003 82 92 54
004 85 65 25
005 89 99 55 */

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.