电子邮件地址的动态数据透视

时间:2019-07-09 03:14:50

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

我试图对此进行研究,但找不到类似的东西。我有一个表,该表可能有多次添加和删除的条目。我不知道需要多少列,因此我需要一个Dynamic Pivot。我看到的所有示例都使用Windows函数,但我正在使用电子邮件地址。

表看起来像这样:

Number | Email
--------------
1      | email1@email.com
1      | email2@email.com
1      | email3@email.com
2      | email4@email.com
2      | email5@email.com
3      | email6@email.com
4      | email7@email.com
4      | email8@email.com

我希望表格看起来像这样(包括所有内容时):

Number | Email1           | Email2           | Email3           
---------------------------------------------------------------
1      | email1@email.com | email2@email.com | email3@email.com
2      | email4@email.com | email5@email.com |
3      | email6@email.com |                  |
4      | email7@email.com | email8@email.com |

如果不包括数字1,它看起来像:

Number | Email1           | Email2                     
--------------------------------------------
2      | email4@email.com | email5@email.com 
3      | email6@email.com |
4      | email7@email.com | email8@email.com

感谢您的帮助!

以下是创建模拟表的代码:

CREATE TABLE #table
(number INT, email VARCHAR(30))

INSERT INTO #table (number, email)
VALUES  (1,'email1@email.com')
       ,(1,'email2@email.com')
       ,(1,'email3@email.com')
       ,(2,'email4@email.com')
       ,(2,'email5@email.com')
       ,(3,'email6@email.com')
       ,(4,'email7@email.com')
       ,(4,'email8@email.com')

这与我尝试过的类似,我使用count尝试使其正常工作,但无法完成。

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(Number)
  FROM (SELECT p.Number FROM #table AS p
  GROUP BY p.Name) AS x;

SELECT @columns

SET @sql = N'
SELECT ' + STUFF(@columns, 1, 2, '') + '
FROM
(
  SELECT p.number, p.email
   FROM #test p
) AS j
PIVOT
(
  Count(email) FOR Name IN ('
  + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
  + ')
) AS p;';
PRINT @sql;
EXEC sp_executesql @sql;

1 个答案:

答案 0 :(得分:2)

您首先需要通过在RNO上进行分区来创建Number。 以下查询应执行您想要的操作:

CREATE TABLE #table (Number INT, Email VARCHAR(30))
INSERT INTO #table (Number, Email)
VALUES  (1,'email1@email.com')
       ,(1,'email2@email.com')
       ,(1,'email3@email.com')
       ,(2,'email4@email.com')
       ,(2,'email5@email.com')
       ,(3,'email6@email.com')
       ,(4,'email7@email.com')
       ,(4,'email8@email.com')

SELECT *, ROW_NUMBER() OVER (PARTITION BY Number ORDER BY Number, Email) AS [RNO] INTO #temp FROM #table

DECLARE @DynamicCols NVARCHAR(MAX) = '';
DECLARE @pvt NVARCHAR(MAX) = '';

SET @pvt = STUFF(
  (SELECT DISTINCT N', ' + QUOTENAME([RNO]) FROM #temp FOR XML PATH('')),1,2,N'')

SET @DynamicCols = STUFF(
  (SELECT DISTINCT N', ' + QUOTENAME([RNO]) + ' AS '+ QUOTENAME('Email' + CAST([RNO] AS VARCHAR(MAX))) FROM #temp FOR XML PATH('')),1,2,N'')


EXEC (N'SELECT [Number],'+ @DynamicCols+'
            FROM #temp tmp
        PIVOT (MAX([Email]) FOR RNO IN('+@pvt+')) AS PIV');