SQL row to column column career PIVOT UNPIVOT

Source: Internet
Author: User

1. Basic Tables

2. Row to column, note the use of ISNULL function, in the overall statistics, ISNULL (-,0) is necessary to use

3. The list of career changes, the list of languages, mathematics, English, politics, the conversion to 2 columns, score scname These two columns, is a new column, can be named Score11 Scname22, casual

4. Test scripts

SELECT *  fromdbo. SC--inserting test DataINSERTdbo. SCSELECT NEWID(),'001','Jack1','Mathematics', theUNIONSELECT NEWID(),'002','Jack2','language', -UNIONSELECT NEWID(),'003','Jack3','English', theUNIONSELECT NEWID(),'004','Jack4','political', the--Row to columnSELECT *  fromdbo. Scpivot (SUM(score) forScnameinch(Chinese, maths, English, politics)) asP--Row CareerSELECT *  from (    --here is the row to column    SELECTSno,sname,ISNULLLanguage0) as 'language',ISNULLMathematical0) as 'Mathematics',ISNULLEnglish0) as 'English',ISNULLPolitical0) as 'political'  fromdbo. SC PIVOT (SUM(score) forScnameinch(Chinese, maths, English, politics)) asp) Tunpivot (score forScnameinch(Chinese, maths, English, politics)) as upWHEREScore!=0SELECT *  from (    --here is the row to column    SELECTSno,sname,ISNULLLanguage0) as 'language',ISNULLMathematical0) as 'Mathematics',ISNULLEnglish0) as 'English',ISNULLPolitical0) as 'political'  fromdbo. SC PIVOT (SUM(score) forScnameinch(Chinese, maths, English, politics)) asp) tunpivot (Score11 forSCName22inch(Chinese, maths, English, politics)) as upWHEREScore11!=0

SQL row to column column career PIVOT UNPIVOT

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.