SQL using sum

Asked

Viewed 385 times

3

I have the following structure:

|  Data  |Quantidade|QTCxVer|QTCxBra|
|04.09.18|   10     |   1   |       |
|04.09.18|   30     |       |   3   |
|04.09.18|   40     |       |   4   |
|04.09.18|   50     |   5   |       |
|05.09.18|   20     |   2   |       |
|05.09.18|   10     |       |   1   |
|05.09.18|   30     |   3   |       |

I want to have the following result:

|  Data  |TotalVer|TotalBra|
|04.09.18|   60   |  70    |
|05.09.18|   50   |  10    |

I’m trying this way, but it’s making a mistake:

select
case when QTCxVer <> 0 then
  sum(Quantidade) as "TotalVer"
else
  sum(Quantidade) as "TotalBran"
end
from tb_teste
 group by  data
  • 1

    what error? ah, no "date" failed in select?

  • you need to add up the two columns...

2 answers

7


  • I think I’d put a else 0 end if the column is null it will not add

  • @Rovannlinhalis Sure? I will test

  • certainty not by SGDB, but in postgresql, if a row is null the sum returns null

  • @Rovannlinhalis I posted the test, normal in the 2! Take a look!

  • 1

    @Rbz, "When using GROUP BY, it is necessary to bring the field in question." I think the correct term would not be "necessary", since it is possible to use group by omitting from the select the grouping field (no error, it just gets "hard" to know what that amount - in the case of this question - is related to); I think something like "Whenever you use GROUP BY, it’s better advisable bring the field in question."

  • Agree @rLinhares!

Show 1 more comment

-1

select
    data,
    sum(quantidade * case when qtdcxver is not null and qtdcxver <> 0 then 1 else 0 end) as TotalVer,
    sum(quantidade * case when qtdcxbra is not null and qtdcxbra <> 0 then 1 else 0 end) as TotalBra
from tb_teste
group by data

Browser other questions tagged

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