将 table 的前两列堆叠成一列,保留与第三列的关系

Stack the first two columns of a table into a single column, preserving relationship with third column

这个问题几乎相同,但当时我没有意识到按唯一键对行进行排序id 实际上不在那里。无论如何,让我用正确的模式重复这个问题。


我有一个 table 如下所示:

| seq | code_1 | code_2 | pair_1 |
|-----|--------|--------|--------|
|   1 |     a1 |     b1 |     c1 |
|   2 |     a2 |     b2 | (null) |
|   3 |     a3 | (null) |     c2 |
|   4 |     a4 | (null) | (null) |

我想将 code_1 和 code_2 堆叠到一个列中,这可以通过使用来完成:

select row_number() over (order by seq), code, pair_1 as pair
  from source
       unpivot (code for code_ in (code_1, code_2)) as unpvt;

,产生以下输出:

| seq | code |   pair |
|-----|------|--------|
|   1 |   a1 |     c1 |
|   2 |   b1 |     c1 |
|   3 |   a2 | (null) |
|   4 |   b2 | (null) |
|   5 |   a3 |     c2 |
|   6 |   a4 | (null) |

,但我也想捕获 code_1pair_1 配对的条件,即每当 code 源自 code_1,它将使用中的值pair_1 对于 pair;每当 code 来自 code_2 时,它将始终使用 null 作为 pair.

因此,例如,给定原始 table,目标 table 应该如下所示:

| seq | code |   pair |
|-----|------|--------|
|   1 |   a1 |     c1 |
|   2 |   b1 | (null) |
|   3 |   a2 | (null) |
|   4 |   b2 | (null) |
|   5 |   a3 |     c2 |
|   6 |   a4 | (null) |

DDL:

http://sqlfiddle.com/#!18/3fecf/9

create table source (
  seq    int,
  code_1 varchar(10),
  code_2 varchar(10),
  pair_1 varchar(10)
);
insert into source values
(1, 'a1', 'b1', 'c1'),
(2, 'a2', 'b2', null),
(3, 'a3', null, 'c2'),
(4, 'a4', null, null);

create table target (
  seq    int,
  code   varchar(10),
  pair   varchar(10)
);
insert into target values
(1, 'a1', 'c1'),
(2, 'b1', null),
(3, 'a2', null),
(4, 'b2', null),
(5, 'a3', 'c2'),
(6, 'a4', null);

我可能在这里遗漏了一些东西,但我认为 UNION ALL 可以做到:

WITH CTE AS
(
    SELECT seq, code_1 as code, pair_1, 1 as codeType
    FROM source
    WHERE code_1 IS NOT NULL
    UNION ALL
    SELECT seq, code_2, NULL, 2
    FROM source
    WHERE code_2 IS NOT NULL
) 
SELECT seq, code, pair_1 as pair
FROM CTE
ORDER BY seq, codeType

See a live demo on rextester.