动态行数据到列

Dynamic Row Data into Column

我有一列有 100 行数据。我需要获得前 4 名,但我需要将其转换为列而不是行。喜欢 Col1、Col2、Col3 和 Col4。

我试过了

SELECT 
    MAX (CASE 
            WHEN rss_name = 'BBC-Sports' 
               THEN rss_name 
         END) AS col1,
    MAX (CASE 
            WHEN rss_name = 'Talk Sports' 
               THEN rss_name 
         END) AS col2,
    MAX (CASE 
            WHEN rss_name = 'Sky Sports' 
               THEN rss_name 
         END) AS col3,
    MAX (CASE 
            WHEN rss_name = 'Crick Info' 
               THEN rss_name 
         END) AS col4 
FROM 
    RSS

但它只适用于静态值:

我需要

 Col1,   Col2,       Col3,      Col4
 Sports,Talk Sports,Sky Sports,Crick Info

但由于这不是常量数据,它会发生变化,并且 Col 中的值会不断变化。

您需要使用 Dynamic Pivot。但在你的情况下,除了你需要一个额外的列作为数据透视表中的列名,比如 COL_1, COL_2...

架构:(来自您的图像。最好以文本形式提供此示例数据)。

CREATE TABLE #TAB (Rss_Name VARCHAR(50))

INSERT INTO #TAB
SELECT 'Sports'
UNION ALL
SELECT 'Talk Sports'
UNION ALL
SELECT 'Sky Sports'
UNION ALL
SELECT 'Crick Info'

现在准备您的动态查询如下

DECLARE @SQL VARCHAR(MAX)='',@PVT_COL VARCHAR(MAX)='';

--Preparing Dynamic Column List 
SELECT @PVT_COL =@PVT_COL
+ '[COL_'+CAST(ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS VARCHAR(4))+'],'
FROM #TAB
SELECT @PVT_COL = LEFT(@PVT_COL,LEN(@PVT_COL)-1)


SELECT @SQL = 
'SELECT * FROM (
SELECT Rss_Name
,''COL_''+CAST(ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS VARCHAR(4)) AS COL_NME 
FROM #TAB
)AS A
PIVOT
(
    MAX(Rss_Name) FOR COL_NME IN ('+@PVT_COL+')
)PVT'

EXEC (@SQL)

结果:

+--------+-------------+------------+------------+
| COL_1  |    COL_2    |   COL_3    |   COL_4    |
+--------+-------------+------------+------------+
| Sports | Talk Sports | Sky Sports | Crick Info |
+--------+-------------+------------+------------+

您可以使用派生的 table 来设置您的列顺序,然后在其上使用您的条件聚合。

SELECT 
    MAX(CASE WHEN Col_Rn = 1 THEN Rss_Name END) AS Col1,
    MAX(CASE WHEN Col_Rn = 2 THEN Rss_Name END) AS Col2,
    MAX(CASE WHEN Col_Rn = 3 THEN Rss_Name END) AS Col3,
    MAX(CASE WHEN Col_Rn = 4 THEN Rss_Name END) AS Col4
FROM (
       SELECT    Rss_Name, 
                 Row_Number() OVER (ORDER BY Rss_Name) AS Col_Rn -- set your order here
       FROM      RSS
    ) t