中值定义为
1.如果记录条数奇数时,就是从高到低排序最中间的那条记录
2.如果记录条数为偶数时,就取中间两条记录的平均值--> 测试数据: tb
if object_id('tb') is NOT NULL
   drop table tb
create table tb (A int)insert into tb
select 1 union all
select 1 union all
select 3 union all
select 4 union all
select 5 
SELECT * FROM tb
--1.奇数时 中间值为 3,再往里面插入一条记录
insert into tb select 6 
--2.偶数时 中间值为 (3+4)/2=3.5
请大家赐教。
可参看 以前的 帖子
http://junmail.javaeye.com/blog/180392

解决方案 »

  1.   

    ;with cte as
    (
    SELECT *,row_number() over (order by a) as rn_asc
    ,row_number() over (order by a desc) as rn_desc
    FROM tb
    )
    select avg(a*1.)
    from cte
    where abs(rn_asc-rn_desc)<2
      

  2.   

    ;with cte
    as
    (
    select row_number() over(order by getdate()) rn,count(1) over() c,* from tb
    )
    select * from cte
    where (c%2=0 and (rn=c/2 or rn=c/2+1)) or (c%2!=0 and rn=c/2+1)
      

  3.   

    ;with t as
    (
    select *,id=row_number() over(order by a),c=count(1) over() from tb 
    )
    select avg(a*1.0) from t where (c%2=0 and(id=c/2 or id= c/2+1)) or (c%2=1 and id=c/2+1)