I get the following data from a query:
Service 201 202 401 // 402 etc
A 100 50 20
C 25 0 0
The columns are dynamic. It sometimes there can be just 201, sometimes 200, 201, 202, 204, etc
I want to get the following result:
Service 201 202 503 2xxCount 5xxCount
A 100 50 20 150 20
C 25 0 0 25 0
As I said, the columns are dynamic. i want to calculate sum of all columns whose name starts with 2, as 2xxCount and 5 as 5xxCount.
2
Answers
You can achieve this in 2 steps – first generate the query dynamically, and then execute it:
You should be able to achieve this by a combined use of
narrow
andpivot
:Result:
Only slightly annoying bit is that you have no control over the column order returned by
pivot
but if the max number of columns is fixed you can hard-code a re-order if it’s important to you.