Home >Database >Mysql Tutorial >How to Dynamically Merge Multiple Rows into One Row Based on Test Type in SQL Server?

How to Dynamically Merge Multiple Rows into One Row Based on Test Type in SQL Server?

Linda Hamilton
Linda HamiltonOriginal
2025-01-22 01:08:37781browse

How to Dynamically Merge Multiple Rows into One Row Based on Test Type in SQL Server?

Dynamicly merge multiple rows into one row based on test type (SQL Server)

Question:

We have a table called Result with columns WorkOrder, TestType and Result. We want to group by TestType column and merge multiple rows with the same TestType into one row. However, we don't know how many TestType columns there will be for each Result.

Solution:

To solve this problem, we can use dynamic SQL. The following query works for up to 100 results. For more than 100 results, we can add more Tally to N in CTE CROSS JOIN.

<code class="language-sql">DECLARE @SQL nvarchar(MAX),
        @CRLF nchar(2) = NCHAR(13) + NCHAR(10),
        @MaxTally int;

SELECT @MaxTally = MAX(C)
FROM (SELECT COUNT(*) AS C
      FROM dbo.Result
      GROUP BY WorkOrder,
               TestType) R;

WITH N AS(
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT TOP (@MaxTally) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1, N N2) --100 行,更多行需要添加更多 N
SELECT @SQL = N'WITH RNs AS(' + @CRLF +
              N'    SELECT WorkOrder,' + @CRLF +
              N'           TestType,' + @CRLF +
              N'           Result,' + @CRLF +
              N'           ROW_NUMBER() OVER (PARTITION BY WorkOrder, TestType ORDER BY (SELECT NULL)) AS RN --ORDER BY 应为您的 ID/始终递增列' + @CRLF +
              N'    FROM dbo.Result)' + @CRLF +
              N'SELECT WorkOrder,' + @CRLF +
              N'       TestType,' + @CRLF +
              --由于不知道 SQL Server 版本,因此使用 FOR XML PATH
              STUFF((SELECT N',' + @CRLF +
                            CONCAT(N'       MAX(CASE RN WHEN ',T.I,N' THEN Result END) AS Result',T.I)
                     FROM Tally T
                     ORDER BY T.I ASC
                     FOR XML PATH(N''),TYPE).value('(./text())[1]','nvarchar(MAX)'),1,3,N'') + @CRLF +
              N'FROM RNs R' + @CRLF +
              N'GROUP BY WorkOrder,' + @CRLF +
              N'         TestType;';

PRINT @SQL; --您的好帮手。

EXEC sys.sp_executesql @SQL;</code>

The above is the detailed content of How to Dynamically Merge Multiple Rows into One Row Based on Test Type in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn