2016-04-30 14 views
-1

このSQL Serverクエリを最適化することは可能です。結果なしでOUTER JOINを使用しようとしました。誰でもこのクエリを最適化するのに役立つだろうか?私が言うことができるものから、OPTIMIZE UNION SQL QUERY

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

組合ALL' 'とは対照的に、あなたが実際に' union'をもしかして –

+1

読めるようにこの質問をフォーマットするにはbashを持ってください。 ? – GSerg

+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;