SQL query case: convert a column to a row using UNION ALL.

Source: Internet
Author: User

SQL query case: convert a column to a row using UNION ALL.

After the conversion of rows and columns, you may encounter the need to replace columns.

 

Create table TestColRow (
Name VARCHAR (10 ),
East INT,
South INT,
West INT,
North INT
);

 

Insert into TestColRow
VALUES ('zhang san', 1, 2, 3, 4 );

 

Insert into TestColRow
VALUES ('Lee 4', 5, 6, 7, 8 );

 

 

 

 

 

Processing with UNION ALL

 

SELECT
Name, 'east' AS Place, east AS Value
FROM
TestColRow
UNION ALL
SELECT
Name, 'south' AS Place, south AS Value
FROM
TestColRow
UNION ALL
SELECT
Name, 'west' AS Place, West AS Value
FROM
TestColRow
UNION ALL
SELECT
Name, 'North' AS Place, north AS Value
FROM
TestColRow

 

Name Place Value
--------------------------
Zhang Weidong 1
Li sidong 5
Zhang sannan 2
Li Sinan 6
Zhang Sanxi 3
Li Sisi 7
Zhang sanbei 4
Li sibei 8

 

 

 

Unordered Processing

 


SELECT
ROW_NUMBER () OVER (order by (SELECT 0) AS id,
*
FROM
TestColRow
Unregister (Value FOR Place IN ([East], [South], [West], [North])
AS

 

Result:

 

Id name Value Place
---------------------
1 Zhang San 1 Dong
2 Zhang San 2 Nan
3 Zhang San 3 XI
4 sheets 3 4 north
5 Li Si 5 Dong
6 Li Si 6 Nan
7 Li Si 7 XI
8. Li Si 8 north

 

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.