Skip to content
Advertisement

Aggregate dynamic columns in SQL Server

I have a narrow table containing unique key and source data

Unique_Key System
1 IT
1 ACCOUNTS
1 PAYROLL
2 IT
2 PAYROLL
3 IT
4 HR
5 PAYROLL

I want to be able to pick a system as a base – in this case IT – then create a dynamic SQL query where it counts:

  • distinct unique key in the chosen system
  • proportion of shared unique key with other systems. These systems could be dynamic and there are lot more than 4

I’m thinking of using dynamic SQL and PIVOT to first pick out all the system names outside of IT. Then using IT as a base, join to that table to get the information.

So the resulting table is:

Unique_Key PAYROLL ACCOUNTS HR
1 1 1 0
2 1 0 0
3 0 0 0

What I want is one step further:

Distinct Count IT Key PAYROLL ACCOUNTS HR
3 67% 33% 0%

I can do a simple join with specific case when/sum statement but wondering if there’s a way to do it dynamically so I don’t need to specify every system name.

Appreciate any tips/hints.

Advertisement

Answer

When writing Dynamic Query, you start off with a non-dynamic query. Make sure you gets the result of the query is correct before you convert to dynamic query.

For the result that you required, the query will be

Once you get the result correct, it is not that difficult to convert to dynamic query. Use string_agg() or for xml path for those repeated rows

db<>fiddle demo

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