您仍然可以使用 PIVOT,尽管您必须组成一个数据透视列,为此我使用下面的 ROW_NUMBER() 函数。我在下面允许了 4 个电话号码,只需扩展模式,例如有 2 个位置[4]
,如果您需要满足更多需求。
下面我展示了来自名为“data”的示例表的数据。如果你有一个复杂的查询,你可以先用一个通用表表达式来命名它,即
;with data as (
<your entire complex query that produces the
columns: ContactId, Name, Title, Phone>
)
select ContactID, Name, Title,
[1] as Phone1,
[2] as Phone2,
[3] as Phone3,
[4] as Phone4
from (
select ContactID, Name, Title, Phone,
Row_Number() over (partition by ContactID, Name, Title
order by Phone) RN
from data) p
pivot (max(Phone) for RN in ([1],[2],[3],[4])) v;
SQL小提琴
MS SQL Server 2012 架构设置:
create table data (
ContactID int,
Name varchar(10),
Title varchar(10),
Phone varchar(20));
insert data values
(1234561, 'Jill', 'Employee', 999991),
(1234562, 'Joel', 'Employee', 999992),
(1234567, 'John', 'Manager', 999999),
(1234567, 'John', 'Manager', 888888);
查询 1:
select ContactID, Name, Title,
[1] as Phone1,
[2] as Phone2,
[3] as Phone3,
[4] as Phone4
from (
select ContactID, Name, Title, Phone,
Row_Number() over (partition by ContactID, Name, Title
order by Phone) RN
from data) p
pivot (max(Phone) for RN in ([1],[2],[3],[4])) v;
结果:
| CONTACTID | NAME | TITLE | PHONE1 | PHONE2 | PHONE3 | PHONE4 |
-------------------------------------------------------------------
| 1234561 | Jill | Employee | 999991 | (null) | (null) | (null) |
| 1234562 | Joel | Employee | 999992 | (null) | (null) | (null) |
| 1234567 | John | Manager | 888888 | 999999 | (null) | (null) |