SQL:子查询AVG和计数问题

时间:2018-09-26 10:12:57

标签: sql postgresql count average

我正在尝试列出所有Land.name,它们具有的平均冰山数量和冰山数量均大于平均数量。

CREATE TABLE Land( 
  c_namn VARCHAR(50) NOT NULL UNIQUE,
  code VARCHAR(4) 
);

CREATE TABLE Berg(
  land VARCHAR(4) ,
  Province VARCHAR(50) 
);
SELECT land.c_name, count(berg.land) 
FROM (
  SELECT avg(a.count3) AS avgberg 
  FROM (
    SELECT count(berg.land) as count3 
    FROM berg) AS a
  ) AS b
  INNER JOIN land ON land.code = berg.land
WHERE a.count3 > b.avgberg

运行代码时,我收到错误消息

  

“错误:表” a“的FROM子句条目丢失
  第10行:a.count3> b.avgberg“

2 个答案:

答案 0 :(得分:0)

我这样理解问题:每个土地上都有许多冰山。查找冰山比平均土地多的土地。 可以这样做:

;WITH bergcount AS
(
    SELECT berg.land, count(berg.land) as count3
    FROM berg
    GROUP BY berg.land
)
SELECT land.name, bergcount.count3
FROM bergcount
INNER JOIN land ON land.code = bergcount.land
WHERE bergcount.count3 >
(
    SELECT avg(count3) as avgberg
    FROM bergcount
)

使用您最近发布的新表名,相同的查询将如下所示:

;WITH bergcount AS
(
    SELECT Berg.land, count(Berg.Land) as count3
    FROM Berg
    GROUP BY Berg.land
)
SELECT Land.name, bergcount.count3
FROM bergcount
INNER JOIN Land ON Land.c_namn = bergcount.land
WHERE bergcount.count3 >
(
    SELECT avg(count3) as avgberg
    FROM bergcount
);

答案 1 :(得分:0)

您可以使用以下查询获取所需结果。

Select land.name, count(berg.land) 
from land, berg
where land.name = berg.land
group by land.name having count(berg.land) > (SELECT avg(count(berg.land)) as count3 
                                              FROM berg 
                                              group by land) ;

谢谢 卡皮尔