Sql-Server

動態透視 SQL 表

  • September 11, 2015

每晚dbsize都會載入各種數據庫大小的數據。

dbsize (id, database_name, database_size, insert_date) 

它看起來像這樣:

- 1   dbname1   1000   1/1/1900
- 2   dbname2   2000   1/1/1900 
- 3   dbname3   3000   1/1/1900 
- 4   dbname1   1200   1/2/1900 
- 5   dbname2   2200   1/2/1900

… 等等

我需要得到這樣的結果

- insert_date dbname1 dbname2 dbname3
- 1/1/1900      1000      2000     3000
- 1/2/1900      1200      2200

嘗試使用此 sql,但沒有:

declare @ColumnNames NVARCHAR(MAX) = ''

declare @SQL NVARCHAR(MAX) = ''

select @ColumnNames += QUOTENAME(database_name) + ',' from  dbo.dbsize


set @ColumnNames = LEFT(@ColumnNames, LEN(@ColumnNames)-1) set @SQL = 
'select * from ( select     database_name   ,insert_date    ,id     from
dbo.dbsize) as BASEDATA

PIVOT   (

   count(id)   for database_name   in      ('

       +@ColumnNames + 

       ')  as PivotTable'


execute sp_executesql @SQL

你是如此接近。只有在動態 sql 字元串的末尾缺少括號,即PIVOT的結束括號。

如果您需要能夠處理 dbsize 中具有相同 database_name 的多行,則必須在基礎數據查詢中添加 COUNT 列和 GROUP BY,並在 PIVOT 中將 COUNT(id) 更改為 SUM(count_column)。

DECLARE @ColumnNames nvarchar(MAX) = ''
DECLARE @SQL nvarchar(MAX) = ''

SELECT @ColumnNames += QUOTENAME( database_name) + ',' from (select distinct database_name from dbo.dbsize) t
SET @ColumnNames = LEFT(@ColumnNames, LEN(@ColumnNames)-1) 
SET @SQL = 'SELECT * FROM ( SELECT database_name, COUNT(*) AS cnt FROM dbsize GROUP BY database_name) AS basedata
           PIVOT ( SUM(cnt) FOR database_name IN (' +@ColumnNames + ')) AS PivotTable'
EXECUTE sp_executesql @SQL

SQL小提琴

引用自:https://dba.stackexchange.com/questions/114762