SQL 服务器 2008 R2 table 枢轴
SQL Server 2008 R2 table Pivot
我有一个包含 3 列的 table。
color
列可以是动态的,现在我有4个元素,以后我可以得到6个或更多的元素。
如何编写查询来做到这一点?
谢谢
使用PIVOT
。学习 SQL SERVER – PIVOT and UNPIVOT Table Examples
SELECT Company, red, white, blu, pink
FROM TableName
PIVOT(MAX(Value) FOR Color IN(ed, white, blu, pink))AS Piv
动态枢轴:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Color)
FROM TableName c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Company, ' + @cols + ' from
(
select Company
, value
, color
from TableName
) x
pivot
(
max(value)
for color in (' + @cols + ')
) p '
execute(@query)
您可以使用动态 sql,例如:
CREATE TABLE #t
(
Company CHAR(3) ,
Value INT ,
color NVARCHAR(10)
)
GO
DECLARE @c NVARCHAR(MAX) = '['
DECLARE @s NVARCHAR(MAX) = ''
INSERT INTO #t
VALUES ( 'AAA', 2, 'red' ),
( 'AAA', 2, 'white' ),
( 'BBB', 2, 'white' ),
( 'BBB', 3, 'blue' ),
( 'CCC', 3, 'pink' ),
( 'FFF', 4, 'blue' )
SELECT @c = @c + color + '],['
FROM ( SELECT DISTINCT
color
FROM #t
) AS t
SELECT @c = SUBSTRING(@c, 1, LEN(@c) - 2)
SET @s = ';WITH cte AS
(
SELECT Company, Value, color FROM #t
)
SELECT Company, ' + @c + ' FROM cte
PIVOT(MAX(Value) FOR color IN(' + @c + ')) AS p'
EXEC(@s)
输出:
Company blue pink red white
AAA NULL NULL 2 2
BBB 3 NULL NULL 2
CCC NULL 3 NULL NULL
FFF 4 NULL NULL NULL
在数据透视子句中应用适当的聚合。
我有一个包含 3 列的 table。
color
列可以是动态的,现在我有4个元素,以后我可以得到6个或更多的元素。
如何编写查询来做到这一点?
谢谢
使用PIVOT
。学习 SQL SERVER – PIVOT and UNPIVOT Table Examples
SELECT Company, red, white, blu, pink
FROM TableName
PIVOT(MAX(Value) FOR Color IN(ed, white, blu, pink))AS Piv
动态枢轴:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Color)
FROM TableName c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Company, ' + @cols + ' from
(
select Company
, value
, color
from TableName
) x
pivot
(
max(value)
for color in (' + @cols + ')
) p '
execute(@query)
您可以使用动态 sql,例如:
CREATE TABLE #t
(
Company CHAR(3) ,
Value INT ,
color NVARCHAR(10)
)
GO
DECLARE @c NVARCHAR(MAX) = '['
DECLARE @s NVARCHAR(MAX) = ''
INSERT INTO #t
VALUES ( 'AAA', 2, 'red' ),
( 'AAA', 2, 'white' ),
( 'BBB', 2, 'white' ),
( 'BBB', 3, 'blue' ),
( 'CCC', 3, 'pink' ),
( 'FFF', 4, 'blue' )
SELECT @c = @c + color + '],['
FROM ( SELECT DISTINCT
color
FROM #t
) AS t
SELECT @c = SUBSTRING(@c, 1, LEN(@c) - 2)
SET @s = ';WITH cte AS
(
SELECT Company, Value, color FROM #t
)
SELECT Company, ' + @c + ' FROM cte
PIVOT(MAX(Value) FOR color IN(' + @c + ')) AS p'
EXEC(@s)
输出:
Company blue pink red white
AAA NULL NULL 2 2
BBB 3 NULL NULL 2
CCC NULL 3 NULL NULL
FFF 4 NULL NULL NULL
在数据透视子句中应用适当的聚合。