查询以从多个表中获取键和列

时间:2014-11-26 09:44:23

标签: sql sql-server-2008 tsql

Table1                      
id1_a   id2_a   id3_a   col 1   col2    col3    
1       -1      3       a       b       c   
Table2                      
id1_b   id2_b   id3_b   col 4   col5    col6    
4       6       2005    d       e       f   

所需输出

------                  
key      col1   col2    col3    col 4   col5    col6
1/-1/3   a      b       c       null    null    nul
4/6/2005 null   null    null    d       e       f

需要一个查询来获取输出,如图所示,来自多个表的数据

2 个答案:

答案 0 :(得分:3)

我认为OP想要这个

    Select (id1_a + ' ' +id2_a + ' ' +id3_a) as key, col1  , col2  , col3 , 
    null as col4 , null as col5 , null as col6 from Table1 
    union 
    Select (id1_b + ' ' +id2_b + ' ' +id3_b) as key, null as col1  , null as col2  , 
    null as col3 , col4 , col5 , col6 from Table2

答案 1 :(得分:0)

我已经放了?作为占位符,当你弄清楚这些链接是如何

SELECT (CONCAT(t1.id1_a,'/',t1.id2_a,'/',t1.id3_a) AS Key1, 
       (CONCAT(t2.id1_b,'/',t2.id2_b,'/',t2.id3_b) AS Key2, 
       t1.col1, t1.col2, t1.col3, t2.col4, t2.col5, t2.col6
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.? = t2.?
相关问题