我有一列有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中的值也会不断变化。
答案 0 :(得分:2)
您可以使用派生表来设置列顺序,然后使用条件聚合。
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
答案 1 :(得分:0)
您需要使用Dynamic Pivot
。但是在你的情况下,除了你需要一个额外的列,用于像COL_1, COL_2...
这样的Pivot中的列名。
架构:(来自您的图片。如果您在文本中提供此示例数据,效果会更好。)
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 |
+--------+-------------+------------+------------+