Skip to content
Advertisement

SQL transforming one row to columns with unknown number of distinct values

I have a following database

And the result I want to achieve would look like so, with values for system_code columns being sum of “value”

My problem is that there is over 1000 distinct values for system_code so I can’t type them by hand. Database has nearly billion entries so anything that would calculate quickly would be perfect.

Advertisement

Answer

Just in case, here is a dynamic PIVOT

Example

Returns

enter image description here

Note:

I believe the max number of columns is 1,024 (wide table 30,000).

Personally, I would hate to consume more than 50 columns.

EDIT:

If you have two many columns, you can filter the list by adding a WHERE in the first query and perhaps run it twice (or more). The results would have the same number of rows, just different column sets.

Example

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement