计算同一查询中的中位数

时间:2014-02-07 02:58:55

标签: sql sql-server

我有一张带有浮动列的表。我需要一个中位数(或者例如第一个四分位数),我必须首先计算它,而在其他查询中我计算平均值,总和,记录数等...(全部在一起)。

我的问题是:有没有办法在同一个查询中计算中位数,平均值,总和...?

3 个答案:

答案 0 :(得分:1)

您可以在SQL Server 2005及更高版本中执行以下操作:

SELECT AVG(Salary) as AVERAGE,
       MAX(case when seqnum = cnt / 2 then salary end) as median,
       MAX(SALARY) as MAXIMUM, 
       MIN(SALARY) as MINIMUM,
       SUM(SALARY) as TOTAL,
       TOTAL as NUMBER_OF_EMP
FROM (SELECT e.*, 
             count(*) over () as total,
             row_number() over (order by salary) as seqnum
      FROM TblEmployees e
     ) e

答案 1 :(得分:0)

只需选择两个选择作为子选择

select * from
     (select max(id) mx, min(id) mi, avg(id) av, 
             sum(id) sm
        from test) a,
(select id as median from
    (select id, 
           row_number() over (order by id) rownumber
    from test) x
where rownumber = (select count(*) from test) / 2) b

在这里查看小提琴:http://sqlfiddle.com/#!3/b9d60/6

答案 2 :(得分:0)

我在SQL Server 2012中找到了这个功能,可以实现我想要的功能:

http://technet.microsoft.com/en-us/library/hh231327.aspx

我无法在一个查询中解决问题,但它比我以前的选项更干净。

查看此功能示例:SQLFIDDLE

我有一份员工薪酬表,我可以使用以下功能:

SELECT 
   AVG(Salary) MEAN,
   MAX(MEDIAN) MEDIAN,
   MAX(SALARY) MAXIMUM,
   MIN(SALARY) MINIMUM,
   SUM(SALARY) TOTAL,
   COUNT(*)    NUMBER_OF_EMP
FROM (
    SELECT *, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY Salary) OVER() MEDIAN 
    FROM TblEmployees
) A