Oracle SQL如何查找小于平均值的计数
我的代码如下:Oracle SQL如何查找小于平均值的计数,sql,oracle,oracle-sqldeveloper,Sql,Oracle,Oracle Sqldeveloper,我的代码如下: SELECT number, name, count(*) as "the number of correct answer" FROM table1 NATURAL JOIN table2 WHERE answer = 'T' GROUP BY number, name HAVING count(*) < avg(count(*)) ORDER BY count(*);
SELECT
number,
name,
count(*) as "the number of correct answer"
FROM
table1 NATURAL JOIN table2
WHERE
answer = 'T'
GROUP BY
number,
name
HAVING
count(*) < avg(count(*))
ORDER BY
count(*);
我建议你不要使用自然连接。它们混淆了查询,使查询成为一个维护工具
您可以使用窗口功能:
SELECT t.*
FROM (SELECT number, name,
COUNT(*) as num_correct,
AVG(COUNT(*)) OVER () as avg_num_correct
FROM table1 JOIN
table2
USING (?). -- be explicit about the column name
WHERE answer = 'T'
GROUP BY number, name
) t
WHERE num_correct < avg_num_correct;
与您的查询版本一样,这会过滤掉所有没有正确答案的组。我建议您不要使用自然连接。它们混淆了查询,使查询成为一个维护工具
您可以使用窗口功能:
SELECT t.*
FROM (SELECT number, name,
COUNT(*) as num_correct,
AVG(COUNT(*)) OVER () as avg_num_correct
FROM table1 JOIN
table2
USING (?). -- be explicit about the column name
WHERE answer = 'T'
GROUP BY number, name
) t
WHERE num_correct < avg_num_correct;
与您的查询版本一样,这会过滤掉所有没有正确答案的组。我会将您当前的查询逻辑放入CTE,然后标记过程中的平均计数: 以cte为例 选择编号、名称、计数*作为cnt, 平均计数*超过平均值 来自表1 自然连接表2 其中答案='T' 按编号、名称分组 选择编号、名称、cnt作为计数 来自cte 其中cnt