3 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個贊
使用ROW_NUMBER(),PIVOT以及一些動態(tài)SQL(但沒有必要光標(biāo)):
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)

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個贊
SSRS中的Matrix控件具有動態(tài)列,如果該數(shù)據(jù)仍然綁定到報表,則可以使用它。否則,您將必須創(chuàng)建一個sql sproc,該sql sproc像動態(tài)示例一樣動態(tài)生成sql,然后執(zhí)行它。
- 3 回答
- 0 關(guān)注
- 453 瀏覽
添加回答
舉報