sql—复制行并包含具有交替值的新列

sauutmhj  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(239)

我有一张表格,将美国各州与数百万人口联系起来:

State      | Pop
-----------+-------
California | 39 M
Texas      | 29 M
Florida    | 21 M
New York   | 19 M
Ohio       | 11 M

我需要使用这个表来生成一个新表,其中每个原始行都有一个“a”和“b”行,即如下所示:

State      | Pop  | Switch
-----------+------+-------
California | 39 M |   a
California | 39 M |   b
Texas      | 29 M |   a
Texas      | 29 M |   b
Florida    | 21 M |   a
Florida    | 21 M |   b
New York   | 19 M |   a
New York   | 19 M |   b
Ohio       | 11 M |   a
Ohio       | 11 M |   b

我不能改变原来的table。
有办法吗?

6yt4nkrj

6yt4nkrj1#

你应该使用 cross join ,这是演示。

select 
  *
from myTable
cross join (values ('a'), ('b')) as val (switch)

输出:

state      | pop  | switch
-----------+------+-------
California | 39 M |   a
California | 39 M |   b
Texas      | 29 M |   a
Texas      | 29 M |   b
Florida    | 21 M |   a
Florida    | 21 M |   b
New York   | 19 M |   a
New York   | 19 M |   b
Ohio       | 11 M |   a
Ohio       | 11 M |   b
jmo0nnb3

jmo0nnb32#

这应该给你所需的输出在交替顺序的开关

select state, pop, switch
from (
select state, pop, 'a' as switch
from table
union all
select state, pop, 'b' as switch
from table
)x
order by state, pop, switch;

相关问题