简体   繁体   English

汇总功能无法正常工作

[英]Aggregate function not working as expected

I was writing a query to find the median from a table. 我正在编写查询以从表中查找中位数。 The table had a single column comprising consecutive natural numbers from 1 to 106. 该表具有包含从1到106的连续自然数的单列。

CREATE TABLE med 
AS (SELECT rs 
    FROM ( SELECT rownum rs
           FROM employees
           WHERE employee_id<=106));

I successfully executed the query to find the median of this 106 natural numbers as 53.5 我成功执行了查询,以找到这106个自然数的中位数为53.5

SELECT AVG(median)
FROM (
        SELECT a.rs median
        FROM med a,
             med b
        GROUP BY a.rs
        HAVING  SUM(CASE 
                        WHEN b.rs<=a.rs THEN 1
                        ELSE 0
                    END)>=(COUNT(*)/2)
        AND     SUM(CASE 
                        WHEN b.rs>=a.rs THEN 1
                        ELSE 0
                    END)>=(COUNT(*)/2));

But on using the aggregate function AVG without using subquery like this: 但是在使用聚合函数AVG而不使用像这样的子查询时:

SELECT AVG(a.rs) median
        FROM med a,
             med b
        GROUP BY a.rs
        HAVING  SUM(CASE 
                        WHEN b.rs<=a.rs THEN 1
                        ELSE 0
                    END)>=(COUNT(*)/2)
        AND     SUM(CASE 
                        WHEN b.rs>=a.rs THEN 1
                        ELSE 0
                    END)>=(COUNT(*)/2)

then it doesn't give the expected output as 53.5 rather it gives output as 53, 54. why so? 那么它没有给出预期的输出53.5,而是给出了53、54的输出。为什么会这样呢?

That's because in your first query with subquery, you are calculating the average between the values 53 and 54. 这是因为在使用子查询的第一个查询中,您正在计算值53和54之间的平均值。

On your second query without subquery the aggregation function is executed but it is performed on each value separatly, meaning AVG(53) and AVG(54). 在没有子查询的第二个查询上,将执行聚合函数,但是会分别对每个值执行聚合函数,这意味着AVG(53)和AVG(54)。 That's why you are getting 2 rows back. 这就是为什么您要返回两行的原因。

I hope it's clear to you. 希望您明白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM