Example for SQLServer2005+
First part of the script combines result of the query into a single variable. Thus we have a names of columns in a PIVOT statement.
DECLARE @cols varchar(100),
@dml nvarchar(max)
SET @cols = N''
SELECT @cols += ',[val5' + CAST(ROW_NUMBER() OVER(ORDER BY 1/0) AS varchar(10)) + '],'
+ '[val6' + CAST(ROW_NUMBER() OVER(ORDER BY 1/0) AS varchar(10)) + ']'
FROM (
SELECT TOP 1 t.someColumn
FROM dbo.test138 t
GROUP BY t.someColumn
ORDER BY COUNT(*) DESC
) t2 JOIN dbo.test138 t3 ON t2.someColumn = t3.someColumn
The second part of the instruction dynamically creates SQL, and then use this command.
SET @dml =
'SELECT *
FROM (
SELECT t1.val1, t1.val2, t1.val3, t1.val4,
COALESCE(o2.colName5, o2.colName6) AS colName,
COALESCE(o2.val5, o2.val6) AS val
FROM dbo.test137 t1 CROSS APPLY (
SELECT ''val5'' + CAST(ROW_NUMBER() OVER(ORDER BY 1/0) AS varchar(10)), t2.val5,
''val6'' + CAST(ROW_NUMBER() OVER(ORDER BY 1/0) AS varchar(10)), t2.val6
FROM dbo.test138 t2
WHERE t1.val1 = t2.someColumn
) o(colName5, val5, colName6, val6)
CROSS APPLY (
SELECT o.colName5, NULL, o.val5, NULL
UNION ALL
SELECT NULL, o.colName6, NULL, o.val6
) o2(colName5, colName6, val5, val6)
) x
PIVOT
(
MAX(x.val) FOR colName IN (' + STUFF(@cols, 1, 1, '') + ')
) pvt'
--PRINT @dml
EXEC sp_executesql @dml
See demo on SQLFiddle