使用空值连接两个简单表

时间:2016-07-22 14:34:05

标签: sql sql-server

我正在尝试加入两个看起来像这样的表:

Table A
ID  X
1   0
1   8

Table B
ID  Y
1   0
1   24
1   48

看起来像这样:

Table D
ID    X     Y
1     0     0
1     8     24
1     NULL  48

或者即使这样也可以:

Table C
ID    X     Y
1     0     NULL
1     8     NULL
1     NULL  0 
1     NULL  24 
1     NULL  48

但是这个:

SELECT a.ID, X, Y FROM [Table A] a
LEFT JOIN [Table] b ON a.ID = b.ID
WHERE a.ID = 1
GROUP BY a.ID, X, Y

继续给我这个:

Table X
ID    X     Y
1     0     0
1     0     24
1     0     48
1     8     24 
1     8     48

3 个答案:

答案 0 :(得分:1)

使用union all

select id,x,null y from tablea
union all
select id,null,y from tableb

full join

select a.id,a.x,b.y 
from tablea a
full join tableb b on a.id = b.id

答案 1 :(得分:1)

这将为解决方案提供空值:

SELECT ID, X, null as Y FROM "Table A"
UNION ALL
SELECT ID, null X, Y FROM "Table B"

我希望它有所帮助。

答案 2 :(得分:0)

ROWNUM和CTE:

WITH 
ra AS
 (SELECT ROW_NUMBER() OVER (ORDER BY ID,X) AS row,id,x FROM a)
,rb AS
 (SELECT ROW_NUMBER() OVER (ORDER BY ID,Y) as row,id,y FROM b)

SELECT COALESCE(ra.id,rb.id),x,y
FROM ra
INNER JOIN rb
ON ra.id = rb.id AND ra.row = rb.row