Problems with row-to-column and column-changing in SQL

Source: Internet
Author: User

Problems with row-to-column and column-changing in SQL

This is a common problem and a test question.

1. Row-to-column issues

Simple example

CREATE TABLE#T (MON1INT, MON2INT, MON3INT)GOINSERT  into#TVALUES(1,2,3)GOSELECT *  from#T--row to column; (union ALL)SELECTMON1 from#TUNION  AllSELECTMON2 from#TUNION  AllSELECTMON3 from#TGO--The final optimizationSELECT *  from (SELECTMON1 from#TUNION  AllSELECTMON2 from#TUNION  AllSELECTMON3 from#T) T

A more complex example

Specific implementation code

 --Create a table  GO  CREATE TABLE#T1 (NAMENVARCHAR( -), ChineseNVARCHAR( -), MATHNVARCHAR( -), 中文版NVARCHAR( -)  )  --inserting analog data  SELECT *  from#T1GO  INSERT  into#T1VALUES('Zhang San', the, -, -)  INSERT  into#T1VALUES('John Doe', -, +,NULL)  INSERT  into#T1VALUES('Harry',NULL, -,NULL)  GO  SELECT *  from#T1--Specific code implementation  GO  SELECT *  from (  SELECTNAME as 'name','language'  as 'Subjects', Chinese as 'Achievements'  from#T1UNION  All  SELECTNAME as 'name','Mathematics'  as 'Subjects', MATH as 'Achievements'  from#T1UNION  All  SELECTNAME as 'name','English'  as 'Subjects', 中文版 as 'Achievements'  from#T1) TOrder  byT. Name

Workaround Two

--The static scheme of a career change: unpivot,sql2005 and later versions
  -- method Two; This method automatically removes values that  are null SELECT Name,obj,grade    from #T1    for inch  as Up

This method is also popular on the internet

Information_schema. The columns view gets the columns to construct the rows, and the XML processing is also used.

2 Row career

Simple example

CREATE TABLE#T0 (MON1INT)INSERT  into#T0VALUES(1)INSERT  into#T0VALUES(2)INSERT  into#T0VALUES(3)SELECT *  from#T0--method One is limited to the fact that the data is not duplicatedSELECT(SELECTMON1 from#T0WHEREMON1=1)'1',(SELECTMON1 from#T0WHEREMON1=2)'2',(SELECTMON1 from#T0WHEREMON1=3)'3' 

Problems with row-to-column and column-changing in SQL

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.