SQL四分位数变换

时间:2014-01-30 18:19:54

标签: sql sql-server-2008 pivot percentile

我有一些数据,我想根据行数划分为四分位数。我已经尝试过使用ntile来做这个但是我遇到麻烦的部分是之后转换数据。例如:数据可能会像这样开始:

COLOR
red    
orange 
blue   
purple 
yellow 
black  
pink   
green  

使用ntile我得到:

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

期望的输出:

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

感谢。

1 个答案:

答案 0 :(得分:4)

您可以使用PIVOT获取最终结果,但我还建议使用像row_number()这样的窗口函数来获取它。窗口函数将为color值中的每个ntile创建一个唯一序列。

你应该可以使用:

;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;

请参阅SQL Fiddle with Demo

相关问题