Skip to Main Content

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question.

Asked: June 03, 2019 - 9:20 am UTC

Last updated: June 05, 2019 - 1:42 pm UTC

Version: 19.1.0.00.15

Viewed 10K+ times! This question is

You Asked

Hi Tom,

I want to show the absence of my people in an APEX form / editable grid. The absence is shown for every day and the day column should be generated automatically.

Current SQL code:
with rws as (
  select person.name, 
  absence.start as dy, 
    case
          when absence.type = 'Vacation' then 'V'
          when absence.type = 'Homeoffice' then 'HO'
       end as text 

  from absence
    join person on person.id = absence.person)

  select * from rws
  
  pivot(
    min(text) for dy in ('06.03.2019', '06.04.2019')
    )

It should look the following way:

Persons 06.03.2019 06.04.2019 06.05.2019
Henry HO x V
Tom x HO x

with '06.03.2019' as the sysdate and should show the following e.g. 90 days. This column should be updated automatically, so that I don't need to write all those dates by hand.

Thanks in advance for your help
Patrizia

and Chris said...

The pivot clause doesn't play nice with dynamic values sadly. There are various workarounds, which I discuss in the "Dynamic Column Lists" section of this blog post https://blogs.oracle.com/sql/how-to-convert-rows-to-columns-and-back-again-with-sql-aka-pivot-and-unpivot

If you can get away with numbering the columns, instead of the dates, you can:

- Use dense_rank() to number the dates
- Pivot the result of these numbers, up to however many days you want to show:

with dts as (
  select sysdate+level/5 dt
  from   dual
  connect by level <= 10
), rws as (
  select dense_rank () over (
           order by trunc ( dt )
         ) dr
  from   dts
)
  select * from rws
  pivot (
    count(*) for dr in ( 1, 2, 3, 4 )
  );

1    2    3    4   
   3    5    2    0


Or APEX has pivoting options built-in to interactive reports https://docs.oracle.com/en/database/oracle/application-express/19.1/aeeug/managing-pivot-reports.html#GUID-5B3D9691-91D8-43F0-B43E-293070473CA5

If you need help building the absence query for the pivot, please share:

- create table statements
- insert into statements of sample data
- the output you expect based on these

Is this answer out of date? If it is, please let us know via a Comment

More to Explore

Analytics

Analytic SQL got you confused? Check out Connor McDonald's complete video course.