sql-按分组数据拆分为多列的两列

93ze6v8z  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(369)

我的任务是想出一种翻译以下数据的方法:

Column_A    Column_B
----------------------
    A           AA
    A           BB
    B           CC
    B           DD
    C           EE
    C           FF
    C           GG

A   B   C
----------
AA  CC  EE
BB  DD  FF
        GG

很快。。
列\u b可以是null或空格,两者都可以,列\u a需要是动态的。我试着研究,并已降落在枢轴,但它需要3列转换。我试过这个答案,但结果是

A   B   C
----------
AA  BB  CC
DD  EE  FF
GG

列a至少可以有25条唯一记录。

azpvetkf

azpvetkf1#

你可以用 row_number() 要生成行号,然后进行聚合:

select max(case when a = 'A' then b end) as a,
       max(case when a = 'B' then b end) as b,
       max(case when a = 'C' then b end) as c
from (select t.*, row_number() over (partition by a order by b) as seqnum
      from t
     ) t
group by seqnum
order by seqnum;
szqfcxe2

szqfcxe22#

正如戈登林诺夫所说 row_number() 为了生成行号,然后进行聚合,基于这个和这个答案,我添加了一个temp列作为 row_number() 作为轴心。

DECLARE @PivotColumnNames AS NVARCHAR(MAX),
        @PivotSelectColumnNames AS NVARCHAR(MAX),
        @DynamicPivotQuery AS NVARCHAR(MAX); 

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(COLUMN_A)
FROM (SELECT DISTINCT COLUMN_A FROM t) AS A

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames 
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(COLUMNA) + ', '') AS '
+ QUOTENAME(COLUMN_A)
FROM (SELECT DISTINCT COLUMN_A FROM t) AS A

WITH PivotData
AS (
    SELECT COLUMN_A --The row group
        , ROW_NUMBER() OVER (
                PARTITION BY COLUMN_A ORDER BY COLUMN_A ASC
                ) AS TheRow --The value that will form columns
        ,COLUMN_B
    FROM 
        t
    )
SELECT '+@PivotSelectColumnNames+'
FROM PivotData
PIVOT(max(COLUMN_B) FOR COLUMN_A IN (
            '+@PivotColumnNames+'
            )) AS P

相关问题