Skip to Main Content
  • Questions
  • Presenting table data into a different format

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Felix.

Asked: August 12, 2016 - 11:56 am UTC

Last updated: August 14, 2016 - 5:46 am UTC

Version: 11.1

Viewed 1000+ times

You Asked

I have a table with the following sample data:

Branch Department
======== ==========
Sydney Sales
Sydney Research
Sydney Finance
London Sales
New York Sales
New York IT

How do I present this data in the table as this format:
Branch Sales Research Finance IT
======== ===== ======== ======= ==
Sydney Y Y Y
London Y
New York Y Y

Thanks.

and Chris said...

Do the pivot!

You don't have to pass a column value. You could use min('Y') as the value you're pivoting:

create table t (
  branch varchar2(10),
  dept   varchar2(10)
);
insert into t values ('Sydney','Sales');
insert into t values ('Sydney','Research');
insert into t values ('Sydney','Finance');
insert into t values ('London','Sales');
insert into t values ('New York','Sales');
insert into t values ('New York','IT');

select * from t
pivot (min('Y') for dept in (
  'Sales' as sales, 'Research' as research, 'Finance' as finance, 'IT' as IT)
);

BRANCH    SALES  RESEARCH  FINANCE  IT  
Sydney    Y      Y         Y            
London    Y                             
New York  Y                         Y

Rating

  (1 rating)

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

Comments

Felix Yan, August 13, 2016 - 12:43 am UTC

Thanks for your response, Chris. That will add to my learing of the function pivot.

I wonder what other SQL functions can we use if the departments are varied and are not limited to the four departments?

For example, there might be a new department Marketing or HR.

Thanks,
Felix
Connor McDonald
August 14, 2016 - 5:46 am UTC

Anton from AMIS has a nice little tool for this

https://technology.amis.nl/2006/05/24/dynamic-sql-pivoting-stealing-antons-thunder/

Cheers,
Connor