Question & Answer
Question
Customers migrating to Netezza from databases like MS SQL are accustomed to be able to use a PIVOT operation to transpose their output datasets (so that the rows become columns and the columns become rows). This functionality is not present in all current NPS versions.
Answer
There is already an enhancement request to add PIVOT functionality to NPS
(Enhancement #30497).
Until that is implemented, you can achieve the PIVOT effect with self referencing
joins or conditional sums (using the "sum(case when ..." syntax). See the examples
below based on simple student test scores data:
create table students (sid varchar(11)) ;
insert into students values ('Adam') ;
insert into students values ('Brian') ;
insert into students values ('Charles') ;
insert into students values ('Dave') ;
create table marks (sid varchar(11), subject varchar(11), mark int2) ;
insert into marks values ('Adam', 'English', 20) ;
insert into marks values ('Adam', 'History', 40) ;
insert into marks values ('Adam', 'Science', 60) ;
insert into marks values ('Brian', 'History', 60) ;
insert into marks values ('Brian', 'Science', 80) ;
insert into marks values ('Charles', 'English', 60) ;
insert into marks values ('Charles', 'Science', 20) ;
insert into marks values ('Dave', 'English', 80) ;
insert into marks values ('Dave', 'History', 20) ;
insert into marks values ('Dave', 'Science', 40) ;
-- SR join to get 1 row per student with each subject mark in a separate column
select s.sid, e.mark as english, h.mark as history, c.mark as science
from students as s
left outer join marks as e on (s.sid = e.sid and e.subject = 'English')
left outer join marks as h on (s.sid = h.sid and h.subject = 'History')
left outer join marks as c on (s.sid = c.sid and c.subject = 'Science')
order by 1 ;
-- Conditional sum SQL to get 1 row per subject with count of passing and
-- failing students as columns
select subject,
sum(case when mark >= 50 then 1 else 0 end) as pass,
sum(case when mark < 50 then 1 else 0 end) as fail
from marks
group by 1 order by 1 ;
Was this topic helpful?
Document Information
Modified date:
17 October 2019
UID
swg21669899