How to add columns from different tables?

Asked

Viewed 1,060 times

0

I am trying to assemble an SQL command for my virtual store that returns the total order value, a table of items (pedidoitemaux) and an additional one for the items (pedidoitemadaux). I built a command, but the Mysql error is occurring:

Every derived table must have its Own alias.

Follow the SQL command:

SELECT 
    SUM(Total_P + Total_A) AS Total
FROM
    (SELECT 
        Pi.IdItem,
            SUM(Pi.Quantidade * Pi.ValorUnit) AS Total_P,
            0 AS Total_A
    FROM
        pedidoitemaux Pi
    GROUP BY Pi.IdItem UNION ALL SELECT 
        Pa.IdItem,
            0 AS Total_P,
            SUM(Pa.Quantidadead * Pa.Valorad) AS TotalA
    FROM
        pedidoitemadaux Pa
    GROUP BY Pa.IdItem)

1 answer

1


For the error message, you are only asking for an alias for the derived table:

SELECT 
    SUM(x.Total_P + x.Total_A) AS Total
FROM
    (SELECT 
        Pi.IdItem,
        SUM(Pi.Quantidade * Pi.ValorUnit) AS Total_P,
        0 AS Total_A
    FROM
        pedidoitemaux Pi
    GROUP BY Pi.IdItem 

    UNION ALL 

    SELECT 
       Pa.IdItem,
       0 AS Total_P,
       SUM(Pa.Quantidadead * Pa.Valorad) AS TotalA
    FROM
        pedidoitemadaux Pa
    GROUP BY Pa.IdItem) x
  • 1

    Perfect, Rovann. It worked! Thank you very much, it helped me a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.