SQL Server:获取中值

时间:2014-04-03 16:12:12

标签: sql-server-2008 group-by median

如何从select语句中获取collumn的每个分组值的中值。我想我使用行号,但不知道如何去做。

注意:如果偶数只是中等号。

name size
joe 10
joe 11
joe 19
joe 20
joe 47
sally 3
sally 8
sally 57
john 1
john 3

我想要Joe 19,Sally 8,John 3

1 个答案:

答案 0 :(得分:0)

设置测试数据:

CREATE TABLE #Foo (Name varchar(10), value int)

INSERT #Foo values
  ('joe', 10)
 ,('joe', 11)
 ,('joe', 19)
 ,('joe', 20)
 ,('joe', 47)
 ,('sally', 3)
 ,('sally', 8)
 ,('sally', 57)
 ,('john', 1)
 ,('john', 3)

首先通过,获得正确的订购:

SELECT Name, Value, row_number() over (partition by name order by value) ranking
 from #Foo

第二遍,确定中间项目(如果项目偶数,"第一个"找到的项目总是返回)

;WITH cteRankings (Name, Value, Ranking)
 as (select Name, Value, row_number() over (partition by name order by value) ranking
      from #Foo)
SELECT Name, avg(Ranking) MedianItem
 from cteRankings
 group by Name

最终通过,获取中间项目的详细信息:

;WITH cteRankings (Name, Value, Ranking)
 as (select Name, Value, row_number() over (partition by name order by value) Ranking
      from #Foo)
SELECT cte.Name, cte.Value
  from cteRankings cte
   inner join (--  Median items
               select Name, avg(Ranking) MedianItem
                from cteRankings
                group by Name) xx
    on xx.Name = cte.Name
     and xx.MedianItem = cte.Ranking
 order by cte.Name

作为cte(公用表表达式)完成,因为调用了子查询并且需要引用两次。