SQL Server:数据透视列

问题描述 投票:0回答:1

我有一张这样的桌子:

id EVT 日期
1 M1 2022-01-01
1 M2
1 M3 2023-01-01
2 M7 2024-01-01
2 M9 2025-01-01

我想要一张这样的桌子:

id M1 M2 M3 M7 M9
1 2022-01-01 2023-01-01
2 2024-01-01 2025-01-01

您有 SQL 查询建议来进行此转换吗?

我试过了:

select ID, M1, M2, M3, M7, M9
from Table
pivot (MAX(DATE) FOR EVT in (M1, M2, M3, M7, M9) AS P

我对 EVT 进行了旋转,但每个日期都有一行

id M1 M2 M3 M7 M9
1 2022-01-01
1
1 2023-01-01
sql sql-server t-sql pivot
1个回答
-2
投票

试试这个:

DROP TABLE IF EXISTS #DataSource;

CREATE TABLE #DataSource
(
    [id] INT,
    [EVT] VARCHAR(10),
    [DATE] DATE
);

INSERT INTO #DataSource ([id], [EVT], [DATE])
VALUES (1, 'M1', '2022-01-01'),
       (1, 'M2', NULL),
       (1, 'M3', '2023-01-01'),
       (2, 'M7', '2024-01-01'),
       (2, 'M9', '2025-01-01');

DECLARE @DynamicTSQLStatement NVARCHAR(MAX),
        @DynamicPIVOTColumns NVARCHAR(MAX);

SELECT @DynamicPIVOTColumns = STRING_AGG(CAST(QUOTENAME([EVT]) AS NVARCHAR(MAX)), ',') WITHIN GROUP (ORDER BY [EVT])
FROM
(
    SELECT DISTINCT [EVT]
    FROM #DataSource
   
) DS ([EVT]);

SET @DynamicTSQLStatement = N'
SELECT *
FROM #DataSource
PIVOT
(
    MAX([DATE]) FOR [EVT] IN (' + @DynamicPIVOTColumns + ')
) PVT';

EXEC sp_executesql @DynamicTSQLStatement;

DROP TABLE #DataSource;

您可以在不支持 STRING_AGG 的情况下使用以下内容:

SET @DynamicPIVOTColumns = STUFF
                          (
                                (
                                SELECT ',[' + CAST([EVT] AS VARCHAR(12)) + ']'
                                FROM #DataSource
                                GROUP BY [EVT]
                                ORDER BY [EVT]
                                FOR XML PATH('') ,TYPE
                                ).value('.', 'NVARCHAR(MAX)')
                                ,1
                                ,1
                                ,''
                          );
© www.soinside.com 2019 - 2024. All rights reserved.