In SQL Server, you could easily pivot your columns something like this:
select
pvt.[Nairobi],
pvt.[Milimani],
pvt.[Criminal],
pvt.[1427932800]
from
(select * from test) t
PIVOT
(
count(uid) for [value] in ([Nairobi],[Milimani],[Criminal],[1427932800])
--change the count function and column to match your needs
) as pvt;
Also, as you may see above, you would need to use some kind of aggregate function to use pivot. Hope this helps!
SQL Fiddle Demo
UPDATE
After re-reading your question, I figured that you might be instead looking for something like this:
SELECT
ltrim(substring(t.concat_values, 1, charindex(' ', t.concat_values, 1))) AS first_col
,ltrim(substring(t.concat_values, dbo.GetNthCharacterOccurrence(t.concat_values, ' ', 1), (dbo.GetNthCharacterOccurrence(t.concat_values, ' ', 2) - dbo.GetNthCharacterOccurrence(t.concat_values, ' ', 1)))) AS second_col
,ltrim(substring(t.concat_values, dbo.GetNthCharacterOccurrence(t.concat_values, ' ', 2), (dbo.GetNthCharacterOccurrence(t.concat_values, ' ', 3) - dbo.GetNthCharacterOccurrence(t.concat_values, ' ', 2)))) AS third_col
,ltrim(substring(t.concat_values, dbo.GetNthCharacterOccurrence(t.concat_values, ' ', 3), len(t.concat_values) - dbo.GetNthCharacterOccurrence(t.concat_values, ' ', 3)+1)) AS fourth_col
FROM (
SELECT DISTINCT stuff((
SELECT ' ' + t2.[value]
FROM test t2
WHERE t1.pid = t2.pid
AND t1.mail = t2.mail
FOR XML path('')
), 1, 1, '') AS concat_values
FROM test t1
) t;
SQL Fiddle Demo 2
The trick for this method is to initially create a comma separated list of values using the STUFF
function with XML Path
. Then, break the string based on the position of the string separator which in this case I used space
(' ').
To find the nth occurrence of space, I "borrowed" a function that was written by Tavis Lovell originally in a blog. To split the values into multiple columns, I used substring
, charindex
and the user defined function above as needed.