SQL quartiles transform

I have some data that I would like divided into quartiles based on row count. I've tried using ntile to do this but the part I'm having trouble with is transforing the data afterward. For example: the data may start out like this:

COLOR
red    
orange 
blue   
purple 
yellow 
black  
pink   
green  

using ntile I get:

N | COLOR  
1 | yellow 
1 | red    
2 | purple 
2 | pink   
3 | orange 
3 | green  
4 | blue   
4 | black  

desired output:

1      |2     |3      |4
yellow |purple|orange |blue
red    |pink  |green  |black

Thanks.

Answers


You can use PIVOT to get the final result, but I would also suggest using a windowing function like row_number() to get it. The windowing function will create a unique sequence for each color in your ntile value.

You should be able to use:

;with cte as
(
  select ntile(4) over(order by color desc) n, color 
  from yourtable
) 
select [1], [2], [3], [4]
from
(
  select n, color,
    row_number() over(partition by n order by n) seq
  from cte
) d
pivot
(
  max(color)
  for n in ([1], [2], [3], [4])
) piv;

See SQL Fiddle with Demo


Need Your Help

Send local sqlite file to server

ios iphone ios7

I have a database of many users,which i want to store on both locally and on my server.Whenever user updates any information,i successfully updates it in local database using core database. But how...