Logic for SQL statement - Sum of values between Table A and Table B

Asked

Viewed 34 times

0

To table A is the table that receives several rows containing different values related to table B which is where the items are stored.

Table A

Descrição | Valor
item 1    | 50,00
item 1    | 40,00
item 2    | 10,00

Table B

Descrição | Valor
item 1    | 100,00
item 2    | 100,00

I’m trying to get the statement to select the descriptions from table A whose values are less than table B. The fact that I am grouping is because there are lines with the same description dealing with the same item, but with different values.

SELECT tabela_A.descricao
FROM tabela_A
         INNER JOIN tabela_B
WHERE tabela_A.id = tabela_B.id
  AND (SELECT SUM(tabela_A.valor)
       FROM tabela_A
                INNER JOIN tabela_B
       WHERE tabela_A.id = tabela_B.id
       GROUP BY tabela_B.descricao) < tabela_B.valor
GROUP BY tabela_B.descricao

So it would be more practical, but it is wrong. But it can help to better understand the point I want to reach:

SELECT tabela_A.descricao, SUM(tabela_A.valor) AS _valor
FROM tabela_A
         INNER JOIN tabela_B
WHERE tabela_A.id = tabela_B.id
  AND _valor < tabela_B.valor
GROUP BY tabela_B.descricao

2 answers

0

I think your Inner Join this wrong spoke the cloister ON, I haven’t tried in sqlite but most works different. Besides you are comparing table_a.id with table_a.id and table_b.id with table_b.id

SELECT tabela_A.descricao
FROM tabela_A
         INNER JOIN tabela_B on tabela_b.id = tabela_a.id 
  where(SELECT SUM(tabela_A.valor)
       FROM tabela_A
                INNER JOIN tabela_B on tabela_b.id = tabela_a.id 
       GROUP BY tabela_B.descricao) < tabela_B.valor
GROUP BY tabela_B.descricao
  • Aaah yes... I forgot about this detail. When comparing table A with table A was a lack of attention when posting. I used a fictional example to better understand, but it’s correct in my code. The truth is that I’m thinking that doing everything with SQL will not work, I’ll have to appeal to conditions via PHP. I appreciate your help right now!

0


Would not be:

SELECT tabela_B.descricao
FROM tabela_B INNER JOIN tabela_A ON (tabela_A.descricao = tabela_B.descricao)
GROUP BY tabela_A.descricao
HAVING SUM(tabela_A.valor) < tabela_B.valor
  • Exactly that! As in the second example, I wanted to access the SOMA function to be able to sequence my code. I made different attempts to get here and come across an SQL clause that I had never seen before, aka HAVING. Thank you very much!

Browser other questions tagged

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