Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

peterpan26's avatar

3 tables sum divided by a minus between two fields SQL

hello, i got this three tables on the united on the query and i'm trying to group the value by matricula, but it's saying matricula is ambiguous here's my 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
0 likes
2 replies
Tray2's avatar

That means that you have two columns with the same name, so the database doesn't know which of them to use.

I'v been working with SQL for the past eight years, and I still have no clue what the heck you are trying to do. You use a join to fuse to or more tables into one, but that is not what you are attempting here.

If you read the entire error it will tell you where the error is.

For the love of god use English names on your tables and columns. Share the complete query and not just a portion of it.

jlrdw's avatar

Also you may need the table.field syntax.

Please or to participate in this conversation.