将两个不同的查询结果合并为一个 table
add two different queries result into one table
我有两个不同的查询(结果列数相同)。
我想把两者合二为一 table.
例如我有以下 table:
id country salary
1 us 10000
2 uk 25000
3 us 35000
4 uk 31000
5 uk 26000
现在我有以下疑问:
查询 1:
select * from table where country='us';
和
查询 2:
select * from table where country='uk';
我有一个最终 table 有六列,如:
id1 |country1 | salary 1 | id2 | country2 | salary2
现在,我想将两个查询结果都放在这个 table 中,因此应显示以下输出:
期望的输出:
id1 |country1 | salary 1 | id2 | country2 | salary2
1 | us | 10000 | 2 | uk | 25000
3 | us | 35000 | 4 | uk | 31000
null | null | null | 5 | uk | 26000
我已经试过了,但没有合并结果:
insert into table (id1,country1,salary1)
select id,country,salary
from table1
where country='us';
和
insert into table (id2,country2,salary2)
select id,country,salary
from table1
where country='uk';
但它给出了以下结果:
id1 |country1 | salary 1 | id2 | country2 | salary2
1 | us | 10000 | null | null | null
3 | us | 35000 | null | null | null
null | null | null | 2 | uk | 25000
null | null | null | 4 | uk | 31000
null | null | null | 5 | uk | 26000
请帮帮我:
如果您的 DBMS 支持 window 函数,您可以使用它们适当地加入您的中间结果。
select t1.id, t1.country, t1.salary, t2.id, t2.country, t2.salary
from
(
select *, row_number() over (order by id) rn
from data
where country = 'us'
) t1
full join
(
select *, row_number() over (order by id) rn
from data
where country = 'uk'
) t2 on t1.rn = t2.rn
结果
id country salary id country salary
-------------------------------------------
1 us 10000 2 uk 25000
3 us 35000 4 uk 31000
null null null 5 uk 26000
我有两个不同的查询(结果列数相同)。 我想把两者合二为一 table.
例如我有以下 table:
id country salary
1 us 10000
2 uk 25000
3 us 35000
4 uk 31000
5 uk 26000
现在我有以下疑问:
查询 1:
select * from table where country='us';
和
查询 2:
select * from table where country='uk';
我有一个最终 table 有六列,如:
id1 |country1 | salary 1 | id2 | country2 | salary2
现在,我想将两个查询结果都放在这个 table 中,因此应显示以下输出:
期望的输出:
id1 |country1 | salary 1 | id2 | country2 | salary2
1 | us | 10000 | 2 | uk | 25000
3 | us | 35000 | 4 | uk | 31000
null | null | null | 5 | uk | 26000
我已经试过了,但没有合并结果:
insert into table (id1,country1,salary1)
select id,country,salary
from table1
where country='us';
和
insert into table (id2,country2,salary2)
select id,country,salary
from table1
where country='uk';
但它给出了以下结果:
id1 |country1 | salary 1 | id2 | country2 | salary2
1 | us | 10000 | null | null | null
3 | us | 35000 | null | null | null
null | null | null | 2 | uk | 25000
null | null | null | 4 | uk | 31000
null | null | null | 5 | uk | 26000
请帮帮我:
如果您的 DBMS 支持 window 函数,您可以使用它们适当地加入您的中间结果。
select t1.id, t1.country, t1.salary, t2.id, t2.country, t2.salary
from
(
select *, row_number() over (order by id) rn
from data
where country = 'us'
) t1
full join
(
select *, row_number() over (order by id) rn
from data
where country = 'uk'
) t2 on t1.rn = t2.rn
结果
id country salary id country salary
-------------------------------------------
1 us 10000 2 uk 25000
3 us 35000 4 uk 31000
null null null 5 uk 26000