У меня есть запрос с двумя подзапросами, которые в основном делают то же самое.Я хотел бы выполнить подзапрос только один раз (в рамках функции STUFF
) и использовать результаты вместо повторного выполнения.
SELECT distinct MIN(alert.alert_id) OVER (PARTITION BY CAST(CONVERT(CHAR(17), alert.effective_date,113) as datetime)) as alertId,
CAST(CONVERT(CHAR(17), alert.effective_date, 113) as datetime) as effectiveDate,
STUFF((
SELECT ',' + alert_2.description
FROM alert_table alert_2
INNER JOIN std_alert std_alert_2 on (alert_2.std_alert_id = std_alert_2.std_alert_id)
WHERE CAST(CONVERT(CHAR(17), alert_2.effective_date,113) as datetime) = CAST(CONVERT(CHAR(17), alert.effective_date,113) as datetime)
AND alert_2.client_id = alert.client_id AND (std_alert_2.std_alert_type_id = 2)
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') as alertDescription,
MIN(std_alert_type_id) OVER (PARTITION BY CAST(CONVERT(CHAR(17), alert.effective_date,113) as datetime)) as stdAlertTypeId,
STUFF((
SELECT ',' + CONVERT(varchar(10), alert_2.alert_id)
FROM alert_table alert_2
JOIN std_alert std_alert_2 on (alert_2.std_alert_id = std_alert_2.std_alert_id)
WHERE CAST(CONVERT(CHAR(17), alert_2.effective_date,113) as datetime) = CAST(CONVERT(CHAR(17), alert.effective_date,113) as datetime)
AND alert_2.client_id = alert.client_id
AND (std_alert_2.std_alert_type_id = 2)
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') as groupedAlertIds
FROM alert_table alert
Можно ли выполнить запрос, подобный
SELECT alert_2.description, alert_2.alert_id
FROM alert_table alert_2
JOIN std_alert std_alert_2 on (alert_2.std_alert_id = std_alert_2.std_alert_id)
WHERE CAST(CONVERT(CHAR(17), alert_2.effective_date,113) as datetime) = CAST(CONVERT(CHAR(17), alert.effective_date,113) as datetime)
AND alert_2.client_id = alert.client_id AND (std_alert_2.std_alert_type_id = 2)
и просто повторно используйте результаты этого запроса при вызове STUFF
.Что-то вроде
STUFF((
SELECT ',' + other_result.alert_id
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') as groupedAlertIds