Saturday, May 31, 2008

Creating Column Headings From Data

In this request, they want the last 3 years that anyone was hired to be the column headings.
We need to read the data to get the variables to be used as column headers.
Column Yr1 New_Value Yr1
Column Yr2 New_Value Yr2
Column Yr3 New_Value Yr3

--+- 1 ----------------------------------------------------------------
--| Max will put these all on one line.
--+--------------------------------------------------------------------
Select Max(Case When Rownum = 1 Then Year End) Yr1,
Max(Case When Rownum = 2 Then Year End) Yr2,
Max(Case When Rownum = 3 Then Year End) Yr3
From
--+- 1.1 ----------------------------------------------------------
--| Get a list of years & put them in order.
--+----------------------------------------------------------------
(Select Distinct To_Char(HireDate,'YYYY') Year
From Emp
Order By Year Desc
)
--+----------------------------------------------------------------
Where Rownum <4;
This will generate a one line report:
YR1  YR2  YR3
---- ---- ----
1987 1982 1981

This sets up the columns to be printed with the format required.
Column '&Yr1' Format $999,999
Column '&Yr2' Format $999,999
Column '&Yr3' Format $999,999

--+- 2 ----------------------------------------------------------------
--| Stack them on lines by department.
--+--------------------------------------------------------------------
Select DeptNo,
Sum(Case When Year = '&Yr1' Then Sal End) "&Yr1",
Sum(Case When Year = '&Yr2' Then Sal End) "&Yr2",
Sum(Case When Year = '&Yr3' Then Sal End) "&Yr3"
From
--+- 2.1 ----------------------------------------------------------
--| Convert date & eliminate records not needed.
--+----------------------------------------------------------------
(Select To_Char(Hiredate,'YYYY') Year,
Sal,
Deptno
From Emp
Where To_Char(Hiredate,'YYYY') In ('&Yr1','&Yr2','&Yr3')
)
--+----------------------------------------------------------------
Group By Deptno;
Final Report:
   DEPTNO      1987      1982      1981
--------- --------- --------- ---------
30 . . $9,400
20 $4,100 . $5,975
10 . $1,300 $7,450

No comments:

Post a Comment