我有一个包含3列的表格。
列color
可以是动态的,现在我有4个元素,之后我可以获得6个或更多元素。
如何编写查询来执行此操作?
谢谢
答案 0 :(得分:1)
使用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)
答案 1 :(得分:1)
您可以使用动态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
在pivot子句中应用适当的聚合。