Home > Blockchain >  SQL - grouping Multiple select sums
SQL - grouping Multiple select sums

Time:08-03

Can someone please advise on the following,

I would like to present two sets of data in separate columns - The total amount for each company.

Currently, the results are displayed in the same column and I cannot find a way to split them, does anyone have any recommendations on this?

enter image description here

I would like the data to be presented as

enter image description here

Select Sum(Amount)
from ServerRoomStock
where CompanyName = 'B'
union all
Select Sum(Amount)
from ServerRoomStock
where CompanyName = 'A'

CodePudding user response:

 SELECT B.sum_company_b,A.sum_company_a
 FROM
( 
    Select Sum(Amount)   sum_company_b
   from ServerRoomStock 
   where CompanyName = 'B' 
)B
cross join 
(
  Select Sum(Amount) sum_company_a
  from ServerRoomStock 
  where CompanyName = 'A'
)A

CodePudding user response:

Simply use case expressions to do conditional aggregation:

select sum(case when CompanyName = 'A' then Amount else 0 end) as sumA,
       sum(case when CompanyName = 'B' then Amount else 0 end) as sumB
from ServerRoomStock
where CompanyName in ('A', 'B')
  • Related