8.5 Row-to-column transposition through insertion, during which column names are dynamically generated
Transpose rows to columns dynamically, during which target column names are generated by dynamically computing records and fill all data in the new table sequence.
One task is to get information of each employee’s all sources of income, during which category values are automatically generated, according to Income table.
Name | Source | Income |
---|---|---|
David | Salary | 8000 |
David | Bonus | 15000 |
Daniel | Salary | 9000 |
Andrew | Shares | 26000 |
Andrew | Sales | 23000 |
Robert | Bonus | 13000 |
Each employee may have different sources of income. Below is the desired result:
Category | Source1 | Income1 | Source2 | Income2 |
---|---|---|---|---|
David | Salary | 8000 | Bonus | 15000 |
Daniel | Salary | 9000 | ||
Andrew | Shares | 26000 | Sales | 23000 |
Robert | Bonus | 13000 |
For row-to-column transposition where row values cannot be predetermined, the number of rows and their names also cannot be pre-decided. In this case pivot() function is useless, we need to write code to perform the dynamic transposition instead.
SPL script:
A | B | |
---|---|---|
1 | =connect(“db”) | =A1.query@x(“select * from Income”) |
2 | =B1.group(Name) | =A2.max(~.len()) |
3 | =create(Name, ${B2.(“Source”+string(~)+“, Income”+string(~)).concat@c()}) | |
4 | for A2 | =A4. Name | A4.conj([Source, Income]) |
5 | >A3.record(B4) |
A3 After the Income table is grouped, make the maximum number of members in a group the number of columns, dynamically generate column names and create a table sequence.
A4~B5 Loop through each group to concatenate name, income sources and income amounts into a sequence, and insert them into A3’s table sequence.
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProc_SPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL