重用函数中子查询的结果

时间:2019-03-08 22:05:50

标签: sql subquery aggregate-functions

我有一个查询,其中包含两个基本执行相同操作的子查询。我只想执行一次子查询(在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

0 个答案:

没有答案