Use DISTINCT and SUM in the same Query

Asked

Viewed 190 times

1

Good I have the following query:

SELECT
    SUM(a.valor - a.desconto - a.credito + a.frete)
FROM
    pedidos a,
    cadastro b
WHERE
    a.status = '2' 
    AND a.data >= '2019-03-29' 
    AND a.data <= '2019-04-29'
    AND a.id_cliente = b.id 
    AND b.id_cidade = '2378'

It returns me the value of 10.859,95. This value is correct. However I need to recover some more data and to do so assemble this query:

    SELECT
    SUM(a.valor + a.frete)
FROM
    pedidos a,
    cadastro b,
    produtos_pedidos c
WHERE
    a.status = '2' 
    AND a.data >= '2019-03-29' 
    AND a.data <= '2019-04-29'
    AND a.id_cliente = b.id 
    AND b.id_cidade = '2378'
    AND a.id = c.id_pedido
    AND c.grupo = '234'

The problem is that it returns me a much higher value, so I realized the error. The requests are being duplicated, because in a request I have several produtos_pedidos. How do I make the table SUM requests but without repeating the ID?

  • It would be interesting to use aliases more suggestive than a, b, c. For example p for pedidos, c for cadastro and pp for produtos_pedidos

1 answer

2


Tried to remove the table produtos_pedidos of join and using it in a filter with EXISTS?

SELECT
    SUM(a.valor + a.frete)
FROM
    pedidos a,
    cadastro b
WHERE
    a.status = '2' 
    AND a.data >= '2019-03-29' 
    AND a.data <= '2019-04-29'
    AND a.id_cliente = b.id 
    AND b.id_cidade = '2378'
    and EXISTS(
        SELECT 1
          FROM
              produtos_pedidos c
         WHERE
             c.id_pedido = a.id
             AND c.grupo = '234'
    )
  • Very good, your way worked. But I want to complicate just a little bit more. Supposing I remove the SUM the answer will be the listing of the values, and assuming I wanted you to list all the values and a field c.qtd that is in produtos_pedidos how would the query look? You can edit your reply and put this other option?

  • Hmm, let’s see... valor table pedidos is the sum of some value in produtos_pedidos?

  • No, I just want to do the field listing valor that is in the table pedido and the countryside qtd that is in the table produtos_pedido

Browser other questions tagged

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