0

我想替换以下查询,因为我有性能问题。由于表假脱机操作员(懒惰假脱机),执行计划给了我很多重复

SELECT DISTINCT LOT_0, 
VarCode = STUFF(
    (
    SELECT DISTINCT ', ' + IT6.ID_0
    FROM  TOLOT S
        INNER JOIN  ETMM I ON I.ITMREF_0=S.ITMREF_0
        INNER JOIN  SICOD6 IT6 ON IT6.ID_0=I.TSICOD_6
    WHERE IT6.LNGDES_0 <>'' AND LOT_0 <> '' AND TSICOD_0 = 'OP'
    AND S.LOT_0=S2.LOT_0
    FOR XML PATH (''), TYPE).value ('.[1]', 'nvarchar(max)'), 1, 2, ''
    ),
VarShort = STUFF(
    (
    SELECT DISTINCT ', ' + IT6.SHODES_0
    FROM  TOLOT S
        INNER JOIN  ETMM I ON I.ITMREF_0=S.ITMREF_0
        INNER JOIN  SICOD6 IT6 ON IT6.ID_0=I.TSICOD_6
    WHERE IT6.LNGDES_0 <>'' AND LOT_0 <> '' AND TSICOD_0 = 'OP'
    AND S.LOT_0=S2.LOT_0
    FOR XML PATH (''), TYPE).value ('.[1]', 'nvarchar(max)'), 1, 2, ''
    )
,VarLong = STUFF(
    (
    SELECT DISTINCT ', ' + IT6.LNGDES_0
    FROM  TOLOT S
        INNER JOIN  ETMM I ON I.ITMREF_0=S.ITMREF_0
        INNER JOIN  SICOD6 IT6 ON IT6.ID_0=I.TSICOD_6
    WHERE IT6.LNGDES_0 <>'' AND LOT_0 <> '' AND TSICOD_0 = 'OP'
        AND S.LOT_0=S2.LOT_0
    FOR XML PATH (''), TYPE).value ('.[1]', 'nvarchar(max)'), 1, 2, ''
    )
FROM  TOLOT AS S2
GROUP BY LOT_0

我会很感激你的想法

4

1 回答 1

0

因为您使用的是 SQL Server 2017,所以您可以简单地使用STRING_AGG

SELECT
  S.LOT_0, 
  VarCode  = STRING_AGG(IT6.ID_0, ', '),
  VarShort = STRING_AGG(IT6.SHODES_0, ', '),
  VarLong  = STRING_AGG(IT6.LNGDES_0, ', ')
FROM TOLOT AS S
LEFT JOIN ETMM I
    (INNER JOIN SICOD6 IT6 ON IT6.ID_0 = I.TSICOD_6)
  ON I.ITMREF_0 = S.ITMREF_0
  AND IT6.LNGDES_0 <> '' AND TSICOD_0 = 'OP'
WHERE S.LOT_0 <> ''
GROUP BY
  S.LOT_0;
于 2021-09-08T23:20:25.197 回答