0

我有一张看起来像这样的桌子。

owner     owner_email     customer
dude1     email1          customer1
dude1     email1          customer2
dude1     email1          customer3
dude2     email2          customer4
dude2     email2          customer5

ETC...

我正在寻找以下内容

owner     owner_email     customer1     customer2     customer3 etc

使用此站点上的枢轴示例,我开始看到我需要其他东西来分组,而我没有。在这里使用枢轴是正确的解决方案吗?我有以下使用另一个例子。

SELECT * FROM 
(
SELECT [owner], [owner_email], [customer]
FROM tTableName
) AS source
PIVOT
(
    MAX([customer])
    FOR [customer] IN ([name1][name2][name3][name4][name5])
) as pvt

谢谢。

4

1 回答 1

3

为了做到这一点,您需要考虑将 添加row_number()到您的内部查询中。我正在使用row_numberwithname创建列name1name2等。然后,当您应用 PIVOT 函数时,您将在单独的列中为每个所有者返回客户:

SELECT * 
FROM 
(
  SELECT [owner], [owner_email], [customer],
    'Name'+cast(row_number() over(partition by owner
                                  order by customer) as varchar(50)) name
  FROM tTableName
) AS source
PIVOT
(
    MAX([customer])
    FOR [name] IN ([name1],[name2],[name3],[name4],[name5])
) as pvt;

请参阅SQL Fiddle with Demo

如果您要为每个所有者拥有超过 5 个名称,那么您可以使用动态 SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' 
                        + QUOTENAME('Name'+cast(row_number() over(partition by owner
                                                order by customer) as varchar(50))) 
                    from tTableName
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT  [owner], [owner_email],' + @cols + ' 
            from 
            (
              SELECT [owner], [owner_email], [customer],
                ''Name''+cast(row_number() over(partition by owner
                                              order by customer) as varchar(50)) name
              FROM tTableName
            ) x
            pivot 
            (
                max(customer)
                for name in (' + @cols + ')
            ) p '

execute(@query);

请参阅SQL Fiddle with Demo。这些会产生一个结果:

| OWNER | OWNER_EMAIL |     NAME1 |     NAME2 |     NAME3 |  NAME4 |  NAME5 |
-----------------------------------------------------------------------------
| dude1 |      email1 | customer1 | customer2 | customer3 | (null) | (null) |
| dude2 |      email2 | customer4 | customer5 |    (null) | (null) | (null) |
于 2013-06-20T19:38:44.270 回答