根据 SQL 服务器 table 中存在的行号将项目排到列中

Row items into column based on row number present in SQL Server table

我在 SQL 服务器 table 中有一组车辆故障部件,如下所示:

Vehicle_ID Failed Part RowNumber
1 0001 1
1 0002 1
1 0003 1
1 0001 2
1 0006 2
1 0007 2
1 0001 3
1 0009 3
2 0001 1
2 0002 1
2 0003 2
2 0007 2
3 0006 1
3 0007 1
4 0011 1
4 0015 1
4 0016 1

RowNumber 是我们必须定义行的列。结果 table 如下所示。 failed part 列计数的最大值为 5。

Vehicle_ID Failed Part1 Failed Part2 Failed Part3 Failed Part4 Failed Part5
1 0001 0002 0003
1 0001 0006 0007
1 0001 0009
2 0001 0002
2 0003 0007
3 0006 0007
4 0011 0015 0016

我尝试了下面的语句,但无法得出准确的结果。

WITH cte AS 
(
    SELECT 
        *, 
        ROW_NUMBER() OVER (PARTITION BY Vehicle_ID,RowNumber)
                           ORDER BY [Failed Part]) rn
    FROM 
        VehicleTable
)
SELECT
    Vehicle_ID,
    MAX(CASE WHEN rn = 1 THEN [Failed Part] END) AS FailedPart1,
    MAX(CASE WHEN rn = 2 THEN [Failed Part] END) AS FailedPart2,
    MAX(CASE WHEN rn = 3 THEN [Failed Part] END) AS FailedPart3,
    MAX(CASE WHEN rn = 4 THEN [Failed Part] END) AS FailedPart4,
    MAX(CASE WHEN rn = 5 THEN [Failed Part] END) AS FailedPart5
FROM 
    cte 
GROUP BY
    Vehicle_ID

您代码中的问题非常微妙。您正在做的是在 Vehicle_ID 上分组,问题是输出 table 中每个 Vehicle_ID 有不止一行。相反,您应该做的是通过对您在 cte 中计算的列号 rn 进行分组来修复它:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Vehicle_ID, RowNumber
                                 ORDER BY [Failed Part]) rn
    FROM VehicleTable
)
SELECT
    Vehicle_ID,
    MAX(CASE WHEN rn = 1 THEN [Failed Part] END) AS FailedPart1,
    MAX(CASE WHEN rn = 2 THEN [Failed Part] END) AS FailedPart2,
    MAX(CASE WHEN rn = 3 THEN [Failed Part] END) AS FailedPart3,
    MAX(CASE WHEN rn = 4 THEN [Failed Part] END) AS FailedPart4,
    MAX(CASE WHEN rn = 5 THEN [Failed Part] END) AS FailedPart5
FROM cte 
GROUP BY
    Vehicle_ID, rn

如果您希望您的行按照输出中的顺序排列,您只需在末尾添加 ORDER BY Vehicle_ID, rn

试试看 here.