Question

I am trying to get the sum of a quantity field from my database

the database is set up to look like so

jobno  raw1 qty1  raw2  qty2   raw3  qty3  raw4 qty4
  234    a     3    b      2      a     3     c    1

Is there a way to say this without querying 4 times.

select sum(qty1) from jtjobfil where raw1 = 'a'
select sum(qty2) from jtjobfil where raw2 = 'a'
select sum(qty3) from jtjobfil where raw3 = 'a'
select sum(qty4) from jtjobfil where raw4 = 'a'
Was it helpful?

Solution

Probably not an improvement, but it is ONE query.

select sum(case when raw1 = 'a' then qty1 else 0 end + 
    case when raw2 = 'a' then qty2 else 0 end +
    case when raw3 = 'a' then qty3 else 0 end +
    case when raw4 = 'a' then qty4 else 0 end) as sumqty
from jtjobfil

I think table should be redesigned to be "vertical"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top