Skip to content
Advertisement

Loop to create new columns

Say that I have a SQL Server table which has 4 columns MonthEnd, Gender, Weight and Age.

Now, the MonthEnd go from 201901 through 201912.

I have a process where a run a query which generates a variety of metrics, for instance sum(Weight) and average(Age) for each month.

Right now, I set a where MonthEnd = 201901 when I create the metrics for that month.

The output is a table with 2 columns and 2 rows. The Column1 header is Metric and the Column2 header is 201901 and then row1 column1 says Total_Weight and row1 column2 is the value generated by the sum(weight) function.

Similarly, row2 column1 says Average_Age and row2 column2 is the result of the Average(Age) function.

I have the above done.

Then, I have to rerun the code after changing the where clause to where MonthEnd = 201902 and then the same structure applies to results.

I want to be able to run 201901 through 201912 in one step and have the output reflect 13 columns, namely, column1 would still be the metric with a header “Metric” but the next 12 columns would have headers 201901 through 201912 with the corresponding results for each month included below the headers.

Can T-SQL do this? I feel like I can do it with 1 aggregation function using Pivot but I haven’t figured out how to do multiple aggregate functions at the same time.

Advertisement

Answer

I was able to use pivot approach to generate the desired result

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