2017-12-04 4 views
0

私は2つの異なるクエリを持っています(結果に同じ列数があります)。 両方を1つのテーブルに入れたい。今2つの異なるクエリ結果を1つのテーブルに追加します。

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:

例えば、私は次の表ている

私は1つのファイナルテーブルは以下のように6つの列を持ってい

id1 |country1 | salary 1 | id2 | country2 | salary2 

さて、私は両方のクエリを入れたいが、この表につながるので、次の出力が表示されるはずです。

所望の出力:

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 

を私を助けてください:

+0

ではなく、2つの挿入文はどのよう –

+0

の1つのinsert文にそれらを追加するために参加しますか?私はどのように挿入ステートメントで結合を使用するか分からない。 – Paras

+0

あなたが使用しているDBMSのタグを追加 –

答えて

0

をお使いのDBMSは、ウィンドウ関数をサポートする場合は、あなたが適切にあなたの中間結果を結合するためにそれらを使用することができます。あなたが使用することができます

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 

demo

RESULT

id  country salary id country salary 
------------------------------------------- 
1  us  10000 2 uk  25000 
3  us  35000 4 uk  31000 
null null null 5 uk  26000 
+0

https://stackoverflow.com/questions/47630095/reconciliation-automation-query .....これを手伝ってもらえますか? – Paras

関連する問題