Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

3 tables sql sum divided by a minus between two fields not working

I have 3 tables: formulario, viaverde and reparacoes.
one of the fields is equal in all tables, called matricula, i’m trying to group every arithmetic operation to it.
but i keep getting the error of matricula is ambiguous or synthax errors, how can i achieve this?

i tried the following code:

JOIN (
    SELECT matricula, (total)/(kmsTotais) AS custoKM
    FROM (
        SELECT matricula, SUM(kmfim - quilometragem) AS kmsTotais
        FROM formulario
        GROUP BY matricula
    ) e
    JOIN (
        SELECT matricula, abastecimento_euros as total FROM formulario
        UNION ALL
        SELECT matricula, custo as total FROM viaverde
        UNION ALL
        SELECT matricula, valor as total FROM reparacoes
    ) as subquery
    GROUP BY matricula
) i ON i.matricula = f.matricula

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to qualify matricula with the table aliases to make it unambiguous.

JOIN (
    SELECT e.matricula, SUM(total)/MAX(kmsTotais) AS custoKM
    FROM (
        SELECT matricula, SUM(kmfim - quilometragem) AS kmsTotais
        FROM formulario
        GROUP BY matricula
    ) e
    JOIN (
        SELECT matricula, abastecimento_euros as total FROM formulario
        UNION ALL
        SELECT matricula, custo as total FROM viaverde
        UNION ALL
        SELECT matricula, valor as total FROM reparacoes
    ) as subquery ON e.matricula = subquery.matricula
    GROUP BY e.matricula
) i ON i.matricula = f.matricula

You could also replace ON e.matricula = subquery.matricula with USING (matricula). Since this indicates that the column name is the same in both tables, you don’t need to qualify that column.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading