У меня есть запрос, который использует подзапросы, но я хотел бы сделать его более эффективным и простым в работе.Я смотрю на логику PIVOT, но не могу заставить ее работать.Ниже приведена оригинальная логика подзапроса, кто-нибудь может мне помочь или указать мне правильное направление.
SELECT
Parent.id
,[sitecode]
,[started]
,[completed]
,cast(( completed - started) as time)
,[profileId]
,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'demographic records',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE Child.transactionId =Parent.Id AND child.message like '%Initialized%' AND child.message like '%demographic records%' ORDER BY Child.created DESC) AS Dem
,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'clinical records',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like '%Initialized%' AND child.message like '%clinical records%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS Clincial
,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total valid patient types:',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like 'Total valid patient types:%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS ValidPatientTypes
,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total invalid patient types:',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like 'Total invalid patient types:%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS NotValidPatientTypes
FROM [Backend].[dbo].[Transaction] AS Parent
where completed > '2018-11-17 00:00:00.00' AND transactionType = 'BulkImport' AND profileId = 122
order by sitecode, completed desc
Любая помощь, спасибо.Даже если Pivot не будет работать, кто-то может указать мне на лучшую логику