Saturday, May 31, 2008

Sum Multiple Columns Based on Conditions

If you need to sum several columns based on conditions, try the Case statement as opposed to running multiple queries with the Where.

A Compute was used with Break to get some various calculations at the end of the report.
Clear Screen
Set Space 3

Break on Report
Compute Count Label 'Not Null Count.' -
Sum Label 'Total..........' -
Avg Label 'Average........' -
Min Label 'Minimum........' -
Max Label 'Maximum........' -
Of Sal10 Sal20 Sal30 SalAll -
on Report

Column Year Format A15 Heading 'Year'
Column Sal10 Format 99,999 Heading 'Dept 10|Salary'
Column Sal20 Format 99,999 Heading 'Dept 20|Salary'
Column Sal30 Format 99,999 Heading 'Dept 30|Salary'
Column SalAll Format 99,999 Heading ' Total |Salary'

---------------------------------------------------
Select Year,
Sum(Case When DeptNo = 10
Then Sal End) As Sal10,
Sum(Case When DeptNo = 20
Then Sal End) As Sal20,
Sum(Case When DeptNo = 30
Then Sal End) As Sal30,
Sum( Sal ) As SalAll
From
--------------------------------------------
-- Break it down by year
--------------------------------------------
( Select To_Char(Hiredate,'YYYY') Year,
Sal,
Deptno
From Emp
)
--------------------------------------------
Group by Year;

No comments:

Post a Comment