8.4 Dynamic row-to-column transposition

 

For dynamic row-to-column transposition, the to-be-generated field(s) cannot be predefined but can only be determined according to values of the corresponding original field.

Below is Employee table:

Name Dept Area Salary
David Sales Beijing 8000
Daniel R&D Beijing 15000
Andrew Sales Shanghai 9000
Robert Sales Beijing 26000
Rudy R&D Shanghai 23000

One task is to find average salary of each department in different areas, whose names are uncertain, and the desired result is as follows:

Dept Beijing Shanghai
Sales 13000 11000
R&D 15000 14000

The task involves a row-to-column transposition, during which the names of target fields need to be extracted from the existing field. We can use the pivot() function to handle such dynamic transposition. The function can automatically extract names for the target fields when the target fields are not specified.

SPL script:

A
1 =connect(“db”)
2 =A1.query@x(“select Dept,Area,avg(Salary) as AvgSalary from Employee group by Dept,Area”)
3 =A2.pivot(Dept; Area, AvgSalary)

A1 Connect to the data source.
A2 Get average salary of each department in each area from Employee table grouped by department and area.
A3 Use pivot() function to perform row-to-column transposition; here the target fields are not specified.