简体   繁体   中英

How can I merge rows and columns from two sql tables into one table

I searched for a while but I couldn't find something similar.
I have two tables with data and I want to merge those two in two one.

Tbl1
id nr val1
1  a1  123
2  a2  124
3  a3  125

Tbl2
id nr val2
5  a1  223
6  a2  224
7  a4  225

Resulting table should be something like this.

Tbl
nr val1 val2
a1  123  223
a2  124  224
a3  125    0
a4    0  225

Any help would be appreciated. Thanks in advance.

It is MS SQL and I tried union and join. But they don't do.

if you use MS SQL then you could try full outer join and Isnull function to get the result you need.

SELECT Isnull(tbl1.nr, tbl2.nr) nr, 
    Isnull(tbl1.val1, 0) val1,
      Isnull(Tbl2.val2, 0) val2 FROM tbl1 FULL OUTER JOIN tbl2 ON tbl1.nr = tbl2.nr

You can do it by doing a FULL OUTER JOIN and COALESCE the columns together.

SELECT COALESCE(tbl1.nr,tbl2.nr) AS nr,tbl1.val1,tbl2.val2 
FROM tbl1 FULL OUTER JOIN tbl2 
ON tbl1.nr = tbl2.nr;
SELECT NVL(a1.nr,b1.nr) as nr,
       NVL(a1.val1,0) AS val1,
       NVL(b1.val2,0) AS val2
FROM table1 a1
     FULL OUTER JOIN table2 b1 ON a1.nr = b1.nr
ORDER BY a1.nr;

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