Skip to content
Advertisement

SQL get rows to colums only for 1 row. Pivot not possible

Stored procedure has 2 date parameters:

I have to output the year-months per column in this selection.

I extracted a string with all these months:

Output is a single column with @cols in it, but what I need is (in this case) 12 columns with first column [2020-01], second column [2020-02] etc.

(@cols is not static, it varies with the select on the dates as the number of columns)

I have tried this with a pivot, but since I have no second value to count this will not work.

I really want to avoid having to declare upfront a static number of columns since there is no limit on the number of columns.

Is this even possible ?

What I have now :

But disadvantage : it is static-> always max 30 columns and what if I have less then 30 months.

The date selection can result in 5 months or 25 months. As you can see in the example I initially had a temp table #periodes with all the months from the date-selection and put them in @cols. But hen got stuck to get all content of @cols in a select to columns.

Advertisement

Answer

Not too sure what you are trying to accomplish but what you want should be possible with dynamic sql e.g. here

Here is your code with some ugly updates that im sure you will be able to modify

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