SELECT Union ALL Disregard Arguments

Asked

Viewed 95 times

3

I have This query that sums two results in different tables.

SELECT 
    sum(g) saldo_anterior 
from (
    SELECT 
        SUM(valor_pg) g 
    FROM ctrl_deposito 
    WHERE MONTH(data_pg) < 11 and
    YEAR(data_pg) <= 2016  or
    YEAR(data_pg) < 2016 and
    departamento = "BRADESCO"

    UNION ALL

    SELECT 
        SUM(valor) 
    FROM concessionarias 
    WHERE MONTH(data) < 11 and 
    YEAR(data) <= 2016  or 
    YEAR(data) < 2016 and 
    tipo = "BOLETO" OR 
    tipo = "COPASA" OR 
    tipo = "TELEFONE" OR 
    tipo = "BRADESCO"
) tabela_virtual 

However, she is disregarding the department parameters at the time of the consultation.

Ex.: I have in my tables records where department = 'CEMIG' and no record with department = 'BRADESCO' and yet she is taking the records of 'CEMIG' and adding the sum.

In the individual queries (without using UNIONN ALL), he considers, but when the results are united, all DEPARTMENT AND TYPE parameters are dispensed with and the table data is summed.

What can it be?

1 answer

4


Your problem is being these OR within the query,

first it doesn’t make any sense YEAR(data) <= 2016 or YEAR(data) < 2016, only YEAR(data) <= 2016 is equivalent to this, and then all the operators AND are processed before the operators OR causing it to return possible unwanted results.

the right thing would be:

SELECT 
    sum(g) saldo_anterior 
from (
    SELECT 
        SUM(valor_pg) g 
    FROM ctrl_deposito 
    WHERE MONTH(data_pg) < 11 and
    YEAR(data_pg) <= 2016 and
    departamento = "BRADESCO"

    UNION ALL

    SELECT 
        SUM(valor) 
    FROM concessionarias 
    WHERE MONTH(data) < 11 and 
    YEAR(data) <= 2016 and 
    (tipo = "BOLETO" OR 
    tipo = "COPASA" OR 
    tipo = "TELEFONE" OR 
    tipo = "BRADESCO")
) tabela_virtual

Operators OR between parentheses, so that they are processed first, before the operators AND

  • Thank you. It worked, however I need to use YEAR(data) <= 2016 or YEAR(data) < 2016, otherwise it ignores months older than 11 in previous years, as 12/2014 - 12/2013. Same as in my question https://answall.com/questions/220754/howto select_do-do-m%C3%Aas-e-year-old? noredirect=1#comment452983_220754

  • 1

    so you have to do it like this: WHERE (MONTH(data_pg) < 11 and YEAR(data_pg) <= 2016 OR YEAR(data_pg) < 2016) AND...

  • 1

    Yes. Thank you for your help. It worked perfectly.

Browser other questions tagged

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