[英]SQL Server Convert Rows Into Columns
I have a table like this with 145.695 rows.我有一个这样的表,有 145.695 行。
SERVER![]() |
TAPE![]() |
---|---|
ACS08 ![]() |
M00030L3 ![]() |
ACS08 ![]() |
M00253L3 ![]() |
ACS09 ![]() |
M00580L3 ![]() |
ACS09 ![]() |
M00602L3 ![]() |
ACS10 ![]() |
M00580L4 ![]() |
ACS10 ![]() |
M00602L5 ![]() |
ACS10 ![]() |
M00602L7 ![]() |
Now I want to reach a target table structure like this:现在我想达到这样的目标表结构:
ACS08 ![]() |
ACS09 ![]() |
ACS10 ![]() |
---|---|---|
M00030L3 ![]() |
M00580L3 ![]() |
M00580L4 ![]() |
M00253L3 ![]() |
M00602L3 ![]() |
M00602L5 ![]() |
M00602L7 ![]() |
I need help because I dont know how can I do.我需要帮助,因为我不知道该怎么做。
You can use dynamic pivot to get the desired results.您可以使用动态 pivot 来获得所需的结果。
First we need to generate the dynamic columns based on the [SERVER] column values and then pivot
the values as per the requirement:首先,我们需要根据 [SERVER] 列值生成动态列,然后根据要求
pivot
值:
DECLARE @cols NVARCHAR(MAX), @query NVARCHAR(MAX);
SET @cols = STUFF((SELECT DISTINCT ','+ QUOTENAME([SERVER])
FROM T FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'), 1, 1, ''); --XML way of getting the column values
SET @query = 'SELECT '+@cols+' from
(
SELECT [SERVER], [TAPE], ROW_NUMBER() OVER (PARTITION BY [SERVER] ORDER BY (SELECT NULL)) as RN --We need to add a unique number to select all rows while doing aggregation for the PIVOT
FROM T
)x
PIVOT (max([TAPE]) for [SERVER] in ('+@cols+')
) PVT';
EXECUTE (@query);
Try this:尝试这个:
DECLARE @Columns nvarchar(max), @Sql nvarchar(max);
SELECT
@Columns =
STRING_AGG(
'MAX(CASE [Server] WHEN ' + QUOTENAME([Server], '''') + ' THEN [Tape] END) AS ' + QUOTENAME([Server]),
','
) WITHIN GROUP(ORDER BY [Server])
FROM
(
SELECT [Server] FROM T GROUP BY [Server]
) S;
SET @Sql =
'SELECT ' + @Columns + ' FROM
(SELECT [Server], [Tape], ROW_NUMBER() OVER (PARTITION BY [SERVER] ORDER BY [Server]) as RN FROM T) S
GROUP BY RN'
EXEC(@Sql);
Note: STRING_AGG()
is supported on SQL Server 2017 and later.注意:
STRING_AGG()
在 SQL Server 2017 及更高版本上受支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.