0

所以这里是:我加入了几个表并得到这样的结果:

ContactID    Name    Title      Phone
1234567      John    Manager    999999
1234567      John    Manager    888888

我想在结果中获取唯一的 ContactID 并将另一个电话值设置为“Phone2”。(有2个以上,Phone3,Phone4)

所以我想看到的结果是这样的

ContactID    Name   Title             Phone    Phone2     Phone3    Phone4...
1234567      John   Manager           999999    888888     NULL      NULL  

有什么帮助吗?我尝试使用 Pivot,但似乎聚合函数在这种情况下不起作用。

4

2 回答 2

1

您仍然可以使用 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) |
于 2013-04-02T03:37:44.103 回答
0

如果您愿意,您可以将所有电话号码放在一列中,这可能对您更有用,具体取决于您的情况。

第一个最后一个电话
约翰经理 888888,999999,111111

请参阅http://www.centrolutions.com/blog/post/2010/03/29/Selecting-Multiple-Rows-as-a-Single-Column-in-SQL.aspx

于 2013-04-02T03:56:07.063 回答