昨天http://topic.csdn.net/u/20110519/18/a4d1cc2b-726f-4253-93ae-c6260da833f4.html#replyachor这个贴里面的中位值计算还是没帮我解决!我例一个例子吧!
create table #table(names varchar(20),values int, createdatetime datetime,minvalues int,maxvalues)
{
   select '张三',29,2011-05-20,21,54 union all
   select '李四',34,2011-05-20,21,54 union all   select '李四',32,2011-05-20,21,54 union all   select '李四',23,getdate(),21,54 union all   select '李四',26,getdate(),21,54 union all   select '张三',28,getdate(),21,54 union all
   select '张三',25,getdate(),21,54 union all   select '张三',23,getdate(),21,54 union all   select '张三',35,getdate(),21,54 
}
求values的中位值 

解决方案 »

  1.   

    create table #table(names varchar(20),[values] int, createdatetime datetime,minvalues int,maxvalues INT)
    INSERT #table
    select '张三',29,2011-05-20,21,54 union all
    select '李四',34,2011-05-20,21,54 union all
    select '李四',32,2011-05-20,21,54 union all
    select '李四',23,getdate(),21,54 union all
    select '李四',26,getdate(),21,54 union all
    select '张三',28,getdate(),21,54 union all
    select '张三',25,getdate(),21,54 union all
    select '张三',23,getdate(),21,54 union all
    select '张三',35,getdate(),21,54 
    ;
    WITH cte
    AS
    (
    SELECT TOP 100 PERCENT ROW_NUMBER() OVER (PARTITION BY t.NAMES ORDER BY t.[values]) Row,NAMES,[values] FROM #table t JOIN master.dbo.spt_values s ON s.number<2 WHERE s.[type]='p' 
    )
    SELECT NAMES,AVG([values]) AS [values] FROM cte a WHERE Row = (SELECT MAX(Row)/2 FROM cte b WHERE b.NAMES=a.names) OR a.Row=(SELECT MAX(Row)/2+1 FROM cte b WHERE b.NAMES=a.names) GROUP BY NAMES DROP TABLE #table
    /*
    NAMES                values
    -------------------- -----------
    李四                   29
    张三                   28(2 行受影响)
    */