多列动态数据透视表(Multi Column Dynamic Pivot Table)

2019-09-28 05:34发布

我试图得到一个干净的数据透视表的多个列。

创建输入表

create table #temp (
  ORDER_ID INT NOT NULL,
  TEST_PLAN INT NOT NULL,
  COLLECTION_TYPE INT NOT NULL,
  TEST_GRP INT NOT NULL,
  TEST INT NOT NULL
)

INSERT INTO #temp (ORDER_ID,TEST_PLAN,COLLECTION_TYPE,TEST_GRP,TEST) VALUES (1,1,2,1360942998,1360943100)
INSERT INTO #temp (ORDER_ID,TEST_PLAN,COLLECTION_TYPE,TEST_GRP,TEST) VALUES (2,1,2,1360943006,1360943079)
INSERT INTO #temp (ORDER_ID,TEST_PLAN,COLLECTION_TYPE,TEST_GRP,TEST) VALUES (1,2,2,1360942845,1360943173)
INSERT INTO #temp (ORDER_ID,TEST_PLAN,COLLECTION_TYPE,TEST_GRP,TEST) VALUES (2,2,2,1360942845,1360943134)
INSERT INTO #temp (ORDER_ID,TEST_PLAN,COLLECTION_TYPE,TEST_GRP,TEST) VALUES (3,2,2,1360942845,1360943189)
INSERT INTO #temp (ORDER_ID,TEST_PLAN,COLLECTION_TYPE,TEST_GRP,TEST) VALUES (1,3,2,1360942998,1360943100)

结果...

ORDER_ID PLAN COLLECTION_TYPE TEST_GRP   TEST        
-------- ---- --------------- ---------- ----------
1        1    2               1360942998 1360943100
2        1    2               1360943006 1360943079
1        2    1               1360942845 1360943173
2        2    1               1360942845 1360943134
3        2    1               1360942845 1360943189
1        3    2               1360942998 1360943100

我想以下,其中ORDER_ID追加到COLLECTION_TYPE,TEST_GRP和测试列

PLAN COLLECTION_TYPE_1 TEST_GRP_1 TEST_1     COLLECTION_TYPE_2 TEST_GRP_2 TEST_2     COLLECTION_TYPE_3 TEST_GRP_3 TEST_3
---- ----------------- ---------- ---------- ----------------- ---------- ---------- ----------------- ---------- ----------
1    2                 1360942998 1360943100 2                 1360943006 1360943079  NULL              NULL       NULL
2    1                 1360942845 1360943173 1                 1360942845 1360943134 1                 1360942845 1360943189
3    2                 1360942998 1360943100 NULL              NULL       NULL       NULL              NULL       NULL 

我有这个和它的作品,但一直在寻找的东西有点清洁剂(如很少空值)。

DECLARE  @SQL  NVARCHAR(MAX),
         @Cols NVARCHAR(MAX)

SELECT @cols = STUFF((select ',
MAX(CASE WHEN [TEST_PLAN]=' + CONVERT(VARCHAR,[TEST_PLAN]) + ' AND [ORDER_ID] = ' + CONVERT(VARCHAR,[ORDER_ID]) +
' THEN [TEST_GRP] ELSE NULL END) AS [TEST_GRP_' + CONVERT(VARCHAR,[ORDER_ID]) + '],
MAX(CASE WHEN [TEST_PLAN]=' + CONVERT(VARCHAR,[TEST_PLAN]) + ' AND [ORDER_ID] = ' + CONVERT(VARCHAR,[ORDER_ID]) +
' THEN [TEST_GRP] ELSE NULL END) AS [TEST_' + CONVERT(VARCHAR,[ORDER_ID]) + '],
MAX(CASE WHEN [TEST_PLAN]=' + CONVERT(VARCHAR,[TEST_PLAN]) + ' AND [ORDER_ID] = ' + CONVERT(VARCHAR,[ORDER_ID]) +
' THEN [COLLECTION_TYPE] ELSE NULL END) AS [COLLECTION_TYPE_' + CONVERT(VARCHAR,[ORDER_ID]) + ']'
FROM #temp
ORDER BY [TEST_PLAN],[ORDER_ID] FOR XML PATH(''),type).value('.','varchar(max)'),1,2,'')

SET @SQL = 'SELECT TEST_PLAN,' + @Cols + ' FROM #Temp GROUP BY TEST_PLAN'

EXECUTE( @SQL)

还有就是输出...

TEST_PLAN   TEST_GRP_1  TEST_1      COLLECTION_TYPE_1 TEST_GRP_2  TEST_2      COLLECTION_TYPE_2 TEST_GRP_1  TEST_1      COLLECTION_TYPE_1 TEST_GRP_2  TEST_2      COLLECTION_TYPE_2 TEST_GRP_3  TEST_3      COLLECTION_TYPE_3 TEST_GRP_4  TEST_4      COLLECTION_TYPE_4 TEST_GRP_5  TEST_5      COLLECTION_TYPE_5 TEST_GRP_6  TEST_6      COLLECTION_TYPE_6 TEST_GRP_7  TEST_7      COLLECTION_TYPE_7 TEST_GRP_8  TEST_8      COLLECTION_TYPE_8 TEST_GRP_9  TEST_9      COLLECTION_TYPE_9 TEST_GRP_10 TEST_10     COLLECTION_TYPE_10 TEST_GRP_1  TEST_1      COLLECTION_TYPE_1
----------- ----------- ----------- ----------------- ----------- ----------- ----------------- ----------- ----------- ----------------- ----------- ----------- ----------------- ----------- ----------- ----------------- ----------- ----------- ----------------- ----------- ----------- ----------------- ----------- ----------- ----------------- ----------- ----------- ----------------- ----------- ----------- ----------------- ----------- ----------- ----------------- ----------- ----------- ------------------ ----------- ----------- -----------------
1           1360942998  1360942998  2                 1360943006  1360943006  2                 NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL               NULL        NULL        NULL
2           NULL        NULL        NULL              NULL        NULL        NULL              1360942845  1360942845  2                 1360942845  1360942845  2                 1360942845  1360942845  2                 1360942845  1360942845  2                 1360942845  1360942845  2                 1360942845  1360942845  2                 1360942845  1360942845  2                 1360942845  1360942845  2                 1360942845  1360942845  2                 1360942845  1360942845  2                  NULL        NULL        NULL
3           NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL              NULL        NULL        NULL               1360942998  1360942998  2

我已经寻找与最接近的是上面的SQL的解决方案。

由于jlimited

Answer 1:

为了得到你想要的结果,我就必须同时使用UNPIVOTPIVOT功能。 该UNPIVOT将你的价值观从列并将其转换为行和PIVOT采取行并将其转换回列。

有时,它更容易先用查询的静态或硬编码的版本,然后转换为动态SQL。 静态版本将是:

select [Plan],
  Isnull(COLLECTION_TYPE_1, '') COLLECTION_TYPE_1, 
  Isnull(TEST_GRP_1, '') TEST_GRP_1, 
  Isnull(TEST_1, '') TEST_1,
  Isnull(COLLECTION_TYPE_2, '') COLLECTION_TYPE_2, 
  Isnull(TEST_GRP_2, '') TEST_GRP_2, 
  Isnull(TEST_2, '') TEST_2,
  Isnull(COLLECTION_TYPE_3, '') COLLECTION_TYPE_3, 
  Isnull(TEST_GRP_3, '') TEST_GRP_3, 
  Isnull(TEST_3, '') TEST_3
from
(
  select [PLAN], col + '_'+ cast(ORDER_ID as varchar(50)) col, value
  from
  (
    select ORDER_ID,[PLAN],COLLECTION_TYPE,TEST_GRP,TEST
    from temp
  ) s
  unpivot
  (
    value
    for col in (COLLECTION_TYPE,TEST_GRP,TEST)
  ) unpiv
) src
pivot
(
  max(value)
  for col in (COLLECTION_TYPE_1, TEST_GRP_1, TEST_1,
              COLLECTION_TYPE_2, TEST_GRP_2, TEST_2,
              COLLECTION_TYPE_3, TEST_GRP_3, TEST_3)
) piv

请参阅SQL拨弄演示 。

一旦你的静态版本,那么你可以很容易地将其转换为动态SQL。 生成动态SQL时,您可以创建替换列的列表null和空字符串或清理另一个值值nulls 。 动态SQL代码为:

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

select @cols = STUFF((SELECT ',' + QUOTENAME(col + '_'+ cast(ORDER_ID as varchar(50))) 
                    from temp t
                    cross apply 
                    (
                      select 'COLLECTION_TYPE' col, 1 SortOrder
                      union all
                      select 'TEST_GRP' col, 2 SortOrder
                      union all
                      select 'TEST' col, 3 SortOrder
                    ) c
                    group by col, ORDER_ID, sortorder
                    order by ORDER_ID, sortorder
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsNames = STUFF((SELECT ', IsNull(' + QUOTENAME(col + '_'+ cast(ORDER_ID as varchar(50)))+', '''') as '+QUOTENAME(col + '_'+ cast(ORDER_ID as varchar(50)))
                    from temp t
                    cross apply 
                    (
                      select 'COLLECTION_TYPE' col, 1 SortOrder
                      union all
                      select 'TEST_GRP' col, 2 SortOrder
                      union all
                      select 'TEST' col, 3 SortOrder
                    ) c
                    group by col, ORDER_ID, sortorder
                    order by ORDER_ID, sortorder
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT [PLAN],' + @colsNames + ' from 
             (
                select [PLAN], col + ''_''+ cast(ORDER_ID as varchar(50)) col, value
                from
                (
                  select ORDER_ID,[PLAN],COLLECTION_TYPE,TEST_GRP,TEST
                  from temp
                ) s
                unpivot
                (
                  value
                  for col in (COLLECTION_TYPE,TEST_GRP,TEST)
                ) unpiv
            ) src
            pivot 
            (
                max(value)
                for col in (' + @cols + ')
            ) p '

execute(@query)

请参阅SQL拨弄演示

这两个给出的结果:

| PLAN | COLLECTION_TYPE_1 | TEST_GRP_1 |     TEST_1 | COLLECTION_TYPE_2 | TEST_GRP_2 |     TEST_2 | COLLECTION_TYPE_3 | TEST_GRP_3 |     TEST_3 |
--------------------------------------------------------------------------------------------------------------------------------------------------
|    1 |                 2 | 1360942998 | 1360943100 |                 2 | 1360943006 | 1360943079 |                 0 |          0 |          0 |
|    2 |                 1 | 1360942845 | 1360943173 |                 1 | 1360942845 | 1360943134 |                 1 | 1360942845 | 1360943189 |
|    3 |                 2 | 1360942998 | 1360943100 |                 0 |          0 |          0 |                 0 |          0 |          0 |


文章来源: Multi Column Dynamic Pivot Table