OPTIMIZE UNION SQL QUERY

时间:2016-04-30 10:48:57

标签: sql sql-server

我相信可以优化这个sql-server查询。我尝试过使用OUTER JOIN而没有结果。有人能帮我优化这个查询吗?

SELECT '1' AS CodigoEmpresa,
       T0.CodigoAlmacen,
       '' AS CodigoUbicacion,
       T0.CodigoArticulo,
       T0.Partida,
       CAST(T0.Unidades - ISNULL(T1.Unidades, 0) AS float) AS Unidades,
       T0.FechaCaduca
FROM dbo.ERP_Stock_Entrada_FINAL AS T0
LEFT JOIN dbo.ERP_Stock_Salida_FINAL AS T1 ON T0.CodigoArticulo = T1.CodigoArticulo
AND T0.Partida = T1.Partida
AND T0.CodigoAlmacen = T1.CodigoAlmacen
UNION
SELECT '1' AS CodigoEmpresa,
       T0.CodigoAlmacen,
       '' AS CodigoUbicacion,
       T0.CodigoArticulo,
       T0.Partida,
       CAST(ISNULL(T1.Unidades,0)-T0.Unidades AS FLOAT) AS Unidades,
       T0.Fechacaduca
FROM ERP_Stock_Salida_Final AS T0
LEFT JOIN dbo.ERP_Stock_Entrada_FINAL AS T1 ON T0.CodigoArticulo = T1.CodigoArticulo
AND T0.Partida = T1.Partida
AND T0.CodigoAlmacen = T1.CodigoAlmacen

1 个答案:

答案 0 :(得分:1)

据我所知,你需要一个FULL OUTER JOIN

SELECT '1' AS CodigoEmpresa,
       COALESCE(T0.CodigoAlmacen, T1.CodigoAlmacen) as CodigoAlmacen
       '' AS CodigoUbicacion,
       COALESCE(T0.CodigoArticulo, T1.CodigoArticulo) as CodigoArticulo
       COALESCE(T0.Partida, T1.Partida) as Partida
       CAST(COALESCE(T0.Unidades, 0) - COALESCE(T1.Unidades, 0) AS float) AS Unidades,
       COALESCE(T0.FechaCaduca, T1.FechaCaduca) as FechaCaduca
FROM dbo.ERP_Stock_Entrada_FINAL T0 FULL JOIN
     dbo.ERP_Stock_Salida_FINAL T1
     ON T0.CodigoArticulo = T1.CodigoArticulo AND
        T0.Partida = T1.Partida AND
        T0.CodigoAlmacen = T1.CodigoAlmacen;