8

我需要旋转一列(数字列)。示例需要此数据:

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

任何帮助将不胜感激...

4

5 回答 5

14

使用ROW_NUMBER(),PIVOT和一些动态 SQL(但不需要游标):

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)
于 2008-10-14T01:56:54.580 回答
1

这个相关问题应该有你需要的答案:SQL Server: Examples of PIVOTing String data

SSRS 中的矩阵控件具有动态列,如果此数据无论如何都绑定到报表,那么您可以使用它。否则,您将必须创建一个 sql sproc 来动态生成示例中的 sql,然后执行它。

于 2008-10-13T20:16:18.260 回答
1

只是因为我想获得更多的 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

它可能需要一些调整,但它适用于您的示例

于 2008-10-13T20:29:52.867 回答
1

此处也可以使用合并函数,类似于关于连接数据的其他问题。

如何创建 SQL Server 函数以将子查询中的多行“加入”到单个分隔字段中?

于 2008-10-13T20:44:41.120 回答
0

我不确定你正在做的事情在 SQL 中是否真的可能(或至少是实用的) - 我不确定,因为我仍然不确定你想要做什么。

您可以在客户端应用程序中构建该数据透视表,例如:

select distinct Letter from MyTable

获取字母列表,然后在循环内使用参数化查询:

select Number from MyTable where Letter=:letter

获取每个字母的数字列表。

于 2008-10-13T21:09:42.897 回答