在SQL 2005中的PIVOT
我需要旋转一列(数字列)。 例如需要这个数据:
a 1 a 2 b 3 b 4 c 5 d 6 d 7 d 8 d 9 e 10 e 11 e 12 e 13 e 14
看起来像这样
a 1 2 b 3 4 c 5 d 6 7 8 9 e 10 11 12 13 14
任何帮助将不胜感激…
使用ROW_NUMBER()
, PIVOT
和一些dynamicSQL(但不需要光标):
CREATE TABLE [dbo].[stackoverflow_198716]( [code] [varchar](1) NOT NULL, [number] [int] NOT NULL ) ON [PRIMARY] DECLARE @sql AS varchar(max) DECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE technique DECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE technique SELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + ']' ,@select_list = COALESCE(@select_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + '] AS [col_' + CONVERT(varchar, PIVOT_CODE) + ']' FROM ( SELECT DISTINCT PIVOT_CODE FROM ( SELECT code, number, ROW_NUMBER() OVER (PARTITION BY code ORDER BY number) AS PIVOT_CODE FROM stackoverflow_198716 ) AS rows ) AS PIVOT_CODES SET @sql = ' ;WITH p AS ( SELECT code, number, ROW_NUMBER() OVER (PARTITION BY code ORDER BY number) AS PIVOT_CODE FROM stackoverflow_198716 ) SELECT code, ' + @select_list + ' FROM p PIVOT ( MIN(number) FOR PIVOT_CODE IN ( ' + @pivot_list + ' ) ) AS pvt ' PRINT @sql EXEC (@sql)
仅仅因为我想获得更多的CTE经验,我想出了以下几点:
WITH CTE(CTEstring, CTEids, CTElast_id) AS ( SELECT string, CAST(id AS VARCHAR(1000)), id FROM dbo.Test_Pivot TP1 WHERE NOT EXISTS (SELECT * FROM dbo.Test_Pivot TP2 WHERE TP2.string = TP1.string AND TP2.id < TP1.id) UNION ALL SELECT CTEstring, CAST(CTEids + ' ' + CAST(TP.id AS VARCHAR) AS VARCHAR(1000)), TP.id FROM dbo.Test_Pivot TP INNER JOIN CTE ON CTE.CTEstring = TP.string WHERE TP.id > CTE.CTElast_id AND NOT EXISTS (SELECT * FROM dbo.Test_Pivot WHERE string = CTE.CTEstring AND id > CTE.CTElast_id AND id < TP.id) ) SELECT t1.CTEstring, t1.CTEids FROM CTE t1 INNER JOIN (SELECT CTEstring, MAX(LEN(CTEids)) AS max_len_ids FROM CTE GROUP BY CTEstring) SQ ON SQ.CTEstring = t1.CTEstring AND SQ.max_len_ids = LEN(t1.CTEids) ORDER BY CTEstring GO
它可能需要一些调整,但它与你的例子
这里也可以使用coalesce函数,类似于其他关于连接数据的问题。
如何创build一个SQL Server函数来将多个行从一个子查询连接到单个分隔的字段?
这个相关的问题应该有你需要的答案: SQL Server:PIVOTingstring数据的例子
SSRS中的Matrix控件具有dynamic列,如果无论如何都将此数据绑定到报表,则可以使用该列。 否则,你将不得不创build一个sql sproc来dynamic地在exaamples中生成sql,然后执行它。
我不确定你在做什么是真的可能(或者至less是实际的)在SQL中 – 我不确定,因为我还不确定你想要做什么。
您可以在您的客户端应用程序中构build数据透视表,例如:
select distinct Letter from MyTable
获取字母列表,然后在循环中使用参数化查询:
select Number from MyTable where Letter=:letter
得到每个字母的数字列表。