Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top