2008-10-13 121 views
7

我需要旋轉一列(Numbers列)。 例如需要這樣的數據:sql 2005中的樞軸

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 

任何幫助,將不勝感激......

+0

看起來你需要清理的格式化位。 – 2008-10-13 19:20:43

+0

究竟是什麼意思,「看起來像這樣」?你是否想要一列中的所有數字,用空格分隔? – Blorgbeard 2008-10-13 19:31:44

+0

用逗號分隔的動態列或單列。 – IZar 2008-10-13 19:44:34

回答

1

此相關的問題應該有你需要的答案:SQL Server: Examples of PIVOTing String data

SSRS中的Matrix控件具有動態列,如果無論如何都將此數據綁定到報表,那麼您可以使用該列。否則,你將不得不創建一個sql sproc,動態地在exaamples中生成sql,然後執行它。

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 

它可能需要一些調整,但它與你的榜樣

0

我不知道你在做什麼是真的有可能(或至少實用)的SQL - 我不知道,因爲我還不清楚自己想要什麼做。

你可以建立一個數據透視表在您的客戶端應用程序,例如有:

select distinct Letter from MyTable 

得到的字母列表,然後使用一個循環中參數化查詢:

select Number from MyTable where Letter=:letter 

獲取每封信的號碼列表。

11

使用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)