如何将具有不同值的行转换为不同的列?

时间:2018-12-19 15:16:24

标签: sql sql-server tsql

我有一个查询,返回的内容如下:

+----+------+-------------------+
| ID | Type |      Address      |
+----+------+-------------------+
|  1 |    0 | Some address text |
|  1 |    1 | Some address text |
|  1 |    3 | Some address text |
|  2 |    0 | Some address text |
|  2 |    1 | Some address text |
+----+------+-------------------+

类型的数量是固定的。最多三个。 ID在此表中不是唯一的,但不能超过三个(每个ID一种)。我要创建的表如下:

+----+-------------------+-------------------+-------------------+
| ID |   AddressType0    |   AddressType1    |   AddressType2    |
+----+-------------------+-------------------+-------------------+
|  1 | Some address text | Some address text | Some address text |
|  2 | Some address text | Some address text | Some address text |
|  3 | Some address text | Some address text | Some address text |
|  4 | Some address text | Some address text | Some address text |
|  5 | Some address text | Some address text | Some address text |
+----+-------------------+-------------------+-------------------+

在结果表中ID应该是唯一的。如果原始表中没有适当类型的地址,则结果表中的字段应为null。

1 个答案:

答案 0 :(得分:1)

您可以进行聚合:

with cte as (
     <query here> 
)
select row_number() over (order by id) as id, 
       max(case when type = 0 then address end) as [AddressType0],
       max(case when type = 1 then address end) as [AddressType1],
       max(case when type = 2 then address end) as [AddressType2]
from cte c
group by id;