Split repeating row data into columns – SQL Server

Today a good friend of mine Hardik Vadher asked me a very interesting question related to SQL. I got his email in the evening when I was in a shopping mall. The whole time I was trying to solve his question in my mind while driving back to home.  Soon I realised that I already have a function named ufn_split_string_row_col created a long back, which can easily take care of this by tweaking the query a little bit. It is very simple but I thought to write a blog on it so that any one having same or related kind of question in future can get help from this.

Original Table:

QID QTR QTD
1 Q1 1-Dec
1 Q2 2-Dec
1 Q3 3-Dec
2 Q1 1-Dec
2 Q2 2-Dec
2 Q3 5-Dec
3 Q1 3-Dec
3 Q2 5-Dec
4 Q3 2-Dec

Required Result:

1 Q1 1-Dec Q2 2-Dec Q3 3-Dec
2 Q1 1-Dec Q2 2-Dec Q3 5-Dec
3 Q1 3-Dec Q2 5-Dec NULL NULL
4 Q3 2-Dec NULL NULL NULL NULL

 

Prasad Sahoo

Prasad Sahoo, is an enthusiast of Microsoft technologies in general and a passionate database professional, mainly focusing on SQL Server performance tuning and business intelligence. He has contributed a long time of his career working on SQL Server and other RDBMS. If he is not busy with SQL stuff then he must be watching some Hollywood movies.

Leave a Reply

%d bloggers like this: