通过一次分组2列来执行表中的unpivoting

时间:2014-11-30 08:55:00

标签: sql sql-server-2008-r2 unpivot

我想在下表中执行unpivoting以获得如下所述的输出。

INPUT

====================================
| ID | Subj1 | Mark1 | Subj2 |Mark2|
====================================
|1   | Eng12 | 24    | Mth23 |NULL |
====================================
|2   | PSY42 | 54    |NULL   | NULL|
====================================

输出

====================
| ID | Subj | Mark |
====================
|1   | Eng12 | 24  |
====================
|1   | MTh23 | NULL|
====================
|2   | PSY42 | 54  |
====================

1 个答案:

答案 0 :(得分:3)

根据您的数据和预期输出

SELECT
    id
    , subj1 subj
    , mark1 mark
FROM
    SomeTable
UNION ALL
SELECT
    id
    , subj2
    , mark2
FROM
    SomeTable
WHERE
    subj2 IS NOT NULL
;