使用不同数量的行行到列

时间:2016-11-21 18:43:50

标签: sql-server

我需要转过身来:

Acct    Email                    SomeCategory
0111    abc@abc.com              Commercial
0222    abc@abc.com              Commercial
0333    abc@abc.com              Commercial
0111    joe@joeblow.com          Commercial
0121    joe@joeblow.com          Residential

进入这个:

Acct    Email                    SomeCategory  Acct1    Acct2   Acct3
0111    abc@abc.com              Commercial    0111     0222    0333
0111    joe@joeblow.com          Commercial    0111
0121    joe@joeblow.com          Residential   0121

最多有500个字段(!)。换句话说,每个客户记录(电子邮件地址+类别)可能包含1到500个帐号。

我无法看到如何使用Pivot从Acct列的内容动态创建列名称,因为Acct列中有数千个值,但SQL无法允许,我最多只需要500个

它将在Excel表格中结束。

我知道它看起来很疯狂......这不是我的想法,客户要求它......

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

IF OBJECT_ID('tempdb..#Tbl') IS NOT NULL
    BEGIN
        DROP TABLE #Tbl
    END

CREATE TABLE #Tbl (
    Acct CHAR(4)
    ,Email VARCHAR(100)
    ,SomeCategory VARCHAR(25)
)

INSERT INTO #Tbl VALUES
('0111','abc@abc.com','Commercial')
,('0222','abc@abc.com','Commercial')
,('0333','abc@abc.com','Commercial')
,('0111','joe@joeblow.com','Commercial')
,('0121','joe@joeblow.com','Residential')

DECLARE @Cols as NVARCHAR(MAX)
DECLARE @query as NVARCHAR(MAX)

SET @Cols = STUFF(
    (
       SELECT ',' + QUOTENAME('Acct' + CAST(RowNumber AS NVARCHAR(10)))
       FROM
          (
             SELECT DISTINCT ROW_NUMBER() OVER (PARTITION BY Email, SomeCategory ORDER BY Acct) as RowNumber
             FROM
                #Tbl
          ) t
       WHERE
          t.RowNumber <= 500
       FOR XML PATH(''), TYPE
    ).value('.','NVARCHAR(MAX)')
    ,1,1, '')

SET @query = '
SELECT *
FROM
    (
       SELECT
          Acct
          ,Email
          ,SomeCategory
          ,''Acct'' + CAST((ROW_NUMBER() OVER (PARTITION BY Email, SomeCategory ORDER BY Acct)) AS NVARCHAR(10)) as Col
       FROM
          #Tbl
    ) t
    PIVOT
    (
       MAX(Acct)
       FOR col IN (' + @Cols + ')
    ) p'

EXECUTE (@query)