问题
I asked a very similar question earlier, but the requirements this time are a bit more complex. I have a table that looks like the following:
| id | code_1 | code_2 | pair_1 |
|----|--------|--------|--------|
| 1 | a1 | a2 | b1 |
| 2 | a3 | a4 | (null) |
| 3 | a5 | (null) | b2 |
| 4 | a6 | (null) | (null) |
| 5 | (null) | a7 | b3 |
| 6 | (null) | a8 | (null) |
| 7 | (null) | (null) | b4 |
| 8 | (null) | (null) | (null) |
I want to stack code_1 and code_2 into a single column, which can be done by using:
select id, code, pair_1 as pair
from source
unpivot (code for code_ in (code_1, code_2)) as unpvt;
, which produces the following output:
| id | code | pair |
|----|------|--------|
| 1 | a1 | b1 |
| 1 | a2 | b1 |
| 2 | a3 | (null) |
| 2 | a4 | (null) |
| 3 | a5 | b2 |
| 4 | a6 | (null) |
| 5 | a7 | b3 |
| 6 | a8 | (null) |
, but I also want to capture the condition that code_1
is paired with pair_1
i.e. whenever code
is sourced from code_1
, it will use the value in pair_1
for pair
; and whenever code
is sourced from code_2
, it will always use null
for pair
.
So for example, given the original table, here is what the target table should look like:
| id | code | pair |
|----|------|--------|
| 1 | a1 | b1 |
| 2 | a2 | (null) |
| 3 | a3 | (null) |
| 4 | a4 | (null) |
| 5 | a5 | b2 |
| 6 | a6 | (null) |
| 7 | a7 | (null) |
| 8 | a8 | (null) |
DDL:
http://sqlfiddle.com/#!18/743a5/16
create table source (
id int identity(1, 1) primary key,
code_1 varchar(10),
code_2 varchar(10),
pair_1 varchar(10)
);
insert into source values
('a1', 'a2', 'b1'),
('a3', 'a4', null),
('a5', null, 'b2'),
('a6', null, null),
(null, 'a7', 'b3'),
(null, 'a8', null),
(null, null, 'b4'),
(null, null, null);
create table target (
id int identity(1, 1) primary key,
code varchar(10),
pair varchar(10)
);
insert into target values
('a1', 'b1'),
('a2', null),
('a3', null),
('a4', null),
('a5', 'b2'),
('a6', null),
('a7', null),
('a8', null);
回答1:
Can't you do simple
UNION ALL
?
Try query below
SELECT * FROM
(
SELECT id, code_1 as code, pair_1 as pair FROM source WHERE code_1 IS NOT NULL
UNION ALL
SELECT id, code_2 as code, NULL as pair FROM source WHERE code_2 IS NOT NULL
) UnionTable
ORDER BY id
来源:https://stackoverflow.com/questions/49070676/how-do-i-stack-the-first-two-columns-of-a-table-into-a-single-column-but-also-p