简体   繁体   中英

Using cross join with unnest

I am trying to create some dummy data for testing purposes. Below is a query I have -

select *, LEVEL1, LEVEL2 from table
cross join
(select ('SVC1', 'SVC2') AS LEVEL1 ) b
cross join
(select ('SVC3', 'SVC4') AS LEVEL2 ) b

Current Output

id       num         name           type   occuSVC2ion    location        LEVEL1         LEVEL2
1000056  1326120205  CHRISTOPHER    H      Physical      ASHEVILLE, NC    (SVC1,SVC2)    (SVC3,SVC4)
1030026  1326105     Jennifer Ew    F      None N/A      Meridian, MS     (SVC1,SVC2)    (SVC3,SVC4)

I want the output to be -

id       num         name           type   occuSVC2ion    location        LEVEL1   LEVEL2
1000056  1326120205  CHRISTOPHER    H      Physical      ASHEVILLE, NC    SVC1     SVC3
1000056  1326120205  CHRISTOPHER    H      Physical      ASHEVILLE, NC    SVC1     SVC4
1000056  1326120205  CHRISTOPHER    H      Physical      ASHEVILLE, NC    SVC2     SVC3
1000056  1326120205  CHRISTOPHER    H      Physical      ASHEVILLE, NC    SVC2     SVC4
1030026  1326105     Jennifer Ew    F      None N/A      Meridian, MS     SVC1     SVC3
1030026  1326105     Jennifer Ew    F      None N/A      Meridian, MS     SVC1     SVC4
1030026  1326105     Jennifer Ew    F      None N/A      Meridian, MS     SVC2     SVC3
1030026  1326105     Jennifer Ew    F      None N/A      Meridian, MS     SVC2     SVC4

I'm confused. Why not just do this?

select t.*, v.LEVEL1, v.LEVEL2
from table cross join
     (values ('SCV1', 'SCV3'),
             ('SCV1', 'SCV4'),
             ('SCV2', 'SCV3'),
             ('SCV2', 'SCV4')
     ) v(LEVEL1, LEVEL2);

Or, if you really have more than two pairs, you can use multiple CROSS JOIN s:

select t.*, v1.LEVEL1, v2.LEVEL2
from table cross join
     (values ('SCV1') ('SCV2')
     ) v1(LEVEL1) cross join
     (values ('SCV3'), ('SCV4')
     ) v2(LEVEL2);

Your code is defining a record type with two columns (this is also known as a composite type). That is what parentheses do in this situation, as explained in the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM