azure SQL查询- CROSS APPLY OPENJSON -如何包含PIVOT

jgovgodb  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(84)

我是新的主题,需要您的帮助.我试图通过查询解析JSON字符串,现在需要透视它.我仍然缺少的是PIVOT命令的集成.提前感谢您的支持!!!亲切的问候,迈克尔

验证码:

WITH request
as
(
SELECT requestId,
       property1191,
       '['+replace(replace(property1191, '[', ''), ']', '')+']' as json
from capex_management_requests
)
SELECT P.requestId, property1191, AttsData.[Id], AttsData.[data]
FROM request P CROSS APPLY OPENJSON (P.json, N'$') WITH (
    Id VARCHAR(200) N'$.metaId',
    data VARCHAR(200) N'$.data'
  ) AS AttsData

结果:

请求ID身份证资料
1六九零1
1一一九二四三五五
1六九零
1一一九二小行星4250
六九零1
一一九二四二二七
六九零
一一九二四千三百

目标:

请求ID六九零一一九二
11四三五五
1小行星4250
1四二二七
四千三百
yvfmudvl

yvfmudvl1#

你只需要添加一个PIVOT子句:

WITH request
as
(
    SELECT requestId,
           property1191,
           '['+replace(replace(property1191, '[', ''), ']', '')+']' as json
    from capex_management_requests
)
SELECT *
FROM
(
    SELECT P.requestId, AttsData.[Id], AttsData.[data], ROW_NUMBER() OVER (PARTITION BY P.requestId,AttsData.[Id] ORDER BY (SELECT 1) ) AS row_id
    FROM request P CROSS APPLY OPENJSON (P.json, N'$') 
    WITH 
    (
        Id VARCHAR(200) N'$.metaId',
        data VARCHAR(200) N'$.data'
     ) AS AttsData
) DS
PIVOT 
(
     MAX(data) FOR Id IN ([690], [1192])
) piv;

如果你想要动态的,你需要首先在一个临时表中具体化结果:

DROP TABLE IF EXISTS #DataSource;

WITH request
as
(
SELECT requestId,
       property1191,
       '['+replace(replace(property1191, '[', ''), ']', '')+']' as json
from capex_management_requests
)
SELECT requestId, [690], [1192]
INTO #DataSource
FROM (
    SELECT P.requestId, property1191, AttsData.[Id], AttsData.[data]
    FROM request P CROSS APPLY OPENJSON (P.json, N'$') WITH (
        Id VARCHAR(200) N'$.metaId',
        data VARCHAR(200) N'$.data'
      ) AS AttsData
) src

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

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

SET @DynammicTSQLStatement = N'
SELECT *
FROM #DataSource
PIVOT
(
    MAX([data]) FOR [Id] IN (' + @DynamicPIVOTColumns + ')
) PVT';

EXEC sp_executesql @DynammicTSQLStatement;

相关问题