这是我已经研究了一段时间但没有结果的 sql 问题。
架构是
CREATE TABLE states (
statecode text primary key,
population_2010 integer,
population_2000 integer,
population_1950 integer,
population_1900 integer,
landarea real,
name text,
admitted_to_union text
);
CREATE TABLE counties(
name text,
statecode text references states(statecode),
population_1950 integer,
population_2010 integer
);
CREATE TABLE senators(
statecode text references states(statecode),
name text primary key,
affiliation text,
took_office integer,
born integer);
CREATE TABLE committees(
id text primary key,
parent_committee text references committees(id),
name text,
chairman text references senators(name),
ranking_member text references senators(name)
);
问题是: 返回有多少个州的数量超过县的平均数量
我知道如何计算平均值:
select avg(state_count)
from
(select count(*) as state_count
from counties C
group by C.statecode)
但我想知道我是否可以重用子查询。
像这样(下面的不行):
select count(*) as state_count
from counties C
group by C.statecode
having count(*) > avg(state_count)
这个查询还是没有统计行数,有没有优雅的办法?
编辑: 刚找到示例答案
SELECT COUNT(*)
FROM (SELECT statecode, COUNT(*) AS counts
FROM counties
GROUP BY statecode) s
WHERE s.counts > (SELECT AVG(t.counts)
FROM (SELECT COUNT(*) AS counts
FROM counties
GROUP BY statecode) t);
但是我还是很好奇有没有更好的方法呢?
最佳答案
您提供的示例答案中不经济的部分是这个
SELECT COUNT(*) AS counts
FROM counties
GROUP BY statecode
这部分出现了两次,一次是为了计算平均值,一次是为了找到大于平均值的计数。所以这是我使用 CTE 的尝试,它为这两个目的重用了上面的代码:
WITH c AS
(
SELECT COUNT(*) AS counts
FROM counties
GROUP BY statecode
)
SELECT COUNT(*) FROM c WHERE counts > (SELECT Avg(CAST(counts AS decimal))
FROM c)
关于sql - 取某列的平均值,然后过滤掉所有小于平均值的行,然后统计行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40053394/