Convert a result set using SQL -- convert a result set to multiple rows

Source: Internet
Author: User
Tags case statement

To convert a result set to a column, use the window function and the case clause. to convert a result set to one or more rows, use the case clause and Cartesian product.

As shown in

Figure 1 Table A figure 2 Table B Figure 3

 

Question: How to obtain the result set shown in Figure 3 based on table A and table B? First, evaluate the Cartesian product of table A and Table B, as shown below:

With newtable
(
Select * from
(Select * From) B as tableb,
(Select provincename from a) as tablea
Group by Fujian, Hunan, Zhejiang, provincename
)

Run the preceding SQL statement

Figure 4

Then, use the case statement to obtain the value of each provincename in Table B for judgment and obtain the corresponding cityname.

With newtable
(
Select * from
(Select * From) B as tableb,
(Select provincename from a) as tablea
Group by Fujian, Hunan, Zhejiang, provincename
),

Lasttable
(
Select
Provincename,
Case

When provincename = 'fujian 'Then Fujian
When provincename = 'hunan 'then Hunan
When provincename = 'zhejiang 'Then Zhejiang
Else''
End as cityname
From newtable
)

Select * From lasttable where cityname <>''
Group by provincename, cityname

Run the preceding SQL statement to obtain the result set 5.

Figure 5

The method for converting a column in the result set into multiple rows is similar to the above, and is not described in detail again.

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.