用于合并集合的更好的T-SQL解决方案?

时间:2012-03-28 17:55:21

标签: sql sql-server tsql

给出以下数据/架构:

DECLARE @t1 TABLE (
    Id int NOT NULL
)

DECLARE @t2 TABLE (
    Id INT NOT NULL,
    Val1 CHAR(1) NOT NULL
)

DECLARE @t3 TABLE (
    Id INT NOT NULL,
    Val2 CHAR(1) NOT NULL
)

INSERT INTO @t1 VALUES (1)
INSERT INTO @t2 VALUES (1, 'A')
INSERT INTO @t2 VALUES (1, 'B')
INSERT INTO @t2 VALUES (1, 'C')
INSERT INTO @t3 VALUES (1, '9')
INSERT INTO @t3 VALUES (1, '8')

我希望看到以下结果集:

Id,Val1,Val2
1,'A','9'
1,'B','8'
1,'C',NULL

现在添加以下内容:

INSERT INTO @t3 VALUES (1, '7')
INSERT INTO @t3 VALUES (1, '6')

我想看到这个:

Id,Val1,Val2
1,'A','9'
1,'B','8'
1,'C','7'
1,NULL,'6'

以下是我提出的建议:

DECLARE @t4 TABLE(
    Id INT NOT NULL,
    RowNumber INT NOT NULL,
    Val1 CHAR(1) NULL,
    Val2 CHAR(1) NULL
)

INSERT INTO @t4 (Id, RowNumber, Val1)
    SELECT Id, ROW_NUMBER() OVER(ORDER BY Id), Val1
        FROM @t2

MERGE @t4 T
USING(SELECT Id, ROW_NUMBER() OVER(ORDER BY Id) RowNumber, Val2 FROM @t3) S
ON (T.Id = S.Id AND T.RowNumber = S.RowNumber)
WHEN MATCHED THEN
    UPDATE SET T.Val2 = S.Val2
WHEN NOT MATCHED THEN
    INSERT (Id, RowNumber, Val2) VALUES (Id, RowNumber, Val2);

SELECT Id, Val1, Val2 FROM @t4

但是我想知道是否有人可以提出更简单的东西,使用SELECT和JOIN而不是MERGE

1 个答案:

答案 0 :(得分:1)

;with q2 as (
    select
        Id,
        Val1,
        ROW_NUMBER() OVER(ORDER BY Val1) rn
    from @t2
), q3 as (
    select
        Id,
        Val2,
        ROW_NUMBER() OVER(ORDER BY Val2 DESC) rn
    from @t3
)
select 
    isnull(q2.Id, q3.Id) as Id, 
    q2.Val1, 
    q3.Val2
from 
    q2 full outer join
    q3 on q2.Id = q3.Id and q2.rn = q3.rn