如何从一个州获得平均年龄的多少

时间:2019-02-19 19:23:44

标签: sql

因此,我将使用以下视图:
-国家
-某州人的平均年龄
-与该州平均年龄相同年龄的人

create view myView
as
select state, avg(age), count((select avg(age) from person))
from person
group by state;

我已经尝试过了,但是我只有多少人来自该州。 有人知道我怎么能做到吗?

4 个答案:

答案 0 :(得分:1)

使用子查询

create view myView
as select state,avage,count(*) from 
(select state, avg(age) as avage
from person
group by state
) t group by state,avage

答案 1 :(得分:1)

您可以使用窗口功能:

create view myView as
    select state, avg_age,
           sum(case when age = avg_age then 1 else 0 end) as num_avg_age
    from (select p.*, avg(age) over (partition by state) as avg_age
          from person
         ) p
    group by state;

请注意,age通常是整数。如果您的数据库将整数的平均值计算为十进制数,则计数可能始终为零。

答案 2 :(得分:0)

您需要将查询加入表person并分组以进行计数:

select g.state, g.averageage, count(p.id) counter from (
  select 
    state, 
    avg(age) averageage
  from person
  group by state
) g left join person p
on p.state = g.state and p.age = g.averageage 
group by g.state, g.averageage

id是表person的主键。
参见demo

答案 3 :(得分:0)

另一种方式。基本上与@forpas的解决方案相同,但是使用CTE而不是子查询。

在一个数据集中按州划分平均年龄,然后将其重新加入基表中,以获取年龄匹配的人数。

CREATE VIEW myView
AS

WITH avgAge AS
(
  SELECT 
    state
    ,AVG(age) AS avgAge
  FROM
    person
  GROUP BY 
    state
)
SELECT
  a.state
  a.avgAge,
  COUNT(p.age) AS cntOfAvg
FROM
  person AS p
JOIN 
  avgAge as a
    ON
      a.avgAge = p.age
      AND
      a.state = p.state;