Advertisement
filhotecmail

Union in TwoCte

Jul 27th, 2021
3,688
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 0.98 KB | None | 0 0
  1. WITH CTE  ( DATA,CODPROD,DESCPROD,UNID,QTDTOTALVENDIDA )
  2.   AS (
  3.        SELECT
  4.         B.EA01DATA,
  5.         B.EA03CODEPROD,
  6.         P.CAD_NOMEDOPROD,
  7.         B.EA07UNID,
  8.         SUM( B.EA05QTD )
  9.         FROM ESTOQUEMOVIMENTOB B
  10.         INNER JOIN CADPRODUTOS P ON ( P.CAD_CEAN13 =  B.EA03CODEPROD)
  11.         WHERE B.EA01DATA BETWEEN :PDATEINI AND :PDATEFIM
  12.         GROUP BY
  13.         B.EA01DATA,
  14.         B.EA03CODEPROD,
  15.         P.CAD_NOMEDOPROD,
  16.         B.EA07UNID
  17.     ),
  18.   CTE2( CODPROD,DESCPROD,UNID,QTDTOTALVENDIDA ) AS
  19.   (
  20.      SELECT CODPROD,
  21.             DESCPROD,
  22.             UNID,
  23.             QTDTOTALVENDIDA
  24.       FROM CTE C
  25.   UNION ALL
  26.   SELECT
  27.    P.CAD_CEAN13,
  28.    P.CAD_NOMEDOPROD,
  29.    P.SAID_UNVENDA,
  30.    CAST((0) AS NUMERIC(15,2))QTDTOTALVENDIDA
  31.   FROM CADPRODUTOS P
  32.   )
  33.    SELECT  CODPROD,
  34.            MAX(DESCPROD)DESCPROD,
  35.            MAX(UNID)UNID,
  36.            MAX(COALESCE(QTDTOTALVENDIDA,0))QTDTOTALVENDIDA
  37.    FROM CTE2 CC
  38.    GROUP BY CODPROD
  39.    ORDER BY 4 DESC
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement