Skip to content
Advertisement

Group by column and multiple Rows into One Row multiple columns

Please help me this:

I want to group by column TestType, but Result should be splitted into colunms if they have same TestType

I want SQL to return data in this format

Result# column should be dynamic because each TestType has many Results

Advertisement

Answer

As I mention in the comments, what you need here is a PIVOT or Cross tab; I prefer the latter so what I am going to use.

The non-dynamic solution to this would be as follows:

The problem, however, is that this “locks” you into 3 results, but you suggest there is an indeterminate number of results. Therefore you need a dynamic solution.

The below will work up to 100 results. if you do need more columns than than, then add more CROSS JOINs to N in the CTE Tally. This results is something like this (which is quite messy).

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