subselect的问题

时间:2015-12-09 12:41:34

标签: sql postgresql subquery aggregate

使用PostgreSQL 9.4;数据库:darwincore2。

我想检索这些字段:

species
county
dataeier
county

我希望得到按county分组的所有帖子的计数,仅显示按总计排序的前10个县。我还需要在species上选择不同的,所以如果有50个具有相同名称的物种,则只将其计为1种。并且只计算dataeier包含文字' nngg'。

的帖子

这是我的代码失败:

ERROR:  column "darwincore2.species" must appear in the GROUP BY clause or be used in an aggregate function
LINE 5:         SELECT species, county 
SELECT DC2.county, count(DC2.*) AS nav_county 
FROM darwincore2 AS DC2, (
SELECT COUNT(*), county
FROM (
    SELECT species, county 
    FROM darwincore2
    WHERE darwincore2.dataeier ILIKE '%nngg%'
    GROUP BY county
    ) AS temp
  ) AS DC2DIST
WHERE 
DC2.country ILIKE '%norway%' 
    AND 
DC2.county = DC2DIST.county
GROUP BY DC2.county 
ORDER BY nav_county DESC 
LIMIT 10;

更新

我能够通过此代码获得结果。它似乎比我最初尝试的更简单,并给我正确的计数。

SELECT county, count(DISTINCT species) as nav_county 
FROM darwincore2 
WHERE country ILIKE '%norway%' 
AND dataeier ILIKE '%nngg%' 
GROUP BY county 
ORDER BY nav_county DESC LIMIT 10

给我结果:

Oslo        2254
Bærum       1923
Larvik      1608
Asker       1580
Arendal     1498
Porsgrunn   1405
Nesodden    1317
Bamble      1157
Skien       1123
Fredrikstad 1020

2 个答案:

答案 0 :(得分:1)

尝试此操作,修正'的拼写错误。

SELECT DC2.county, count(DC2.*) AS nav_county 
FROM darwincore2 AS DC2, (
SELECT COUNT(*), county
FROM (
    SELECT species, county 
    FROM darwincore2
    WHERE darwincore2.dataeier ILIKE '%nngg%'
    GROUP BY county
    ) AS temp
  ) AS DC2DIST
WHERE 
DC2.country ILIKE '%norway%' 
    AND 
DC2.county = DC2DIST.county
GROUP BY DC2.county 
ORDER BY nav_county DESC 
LIMIT 10;

答案 1 :(得分:0)

您的问题可能是糟糕的单引号。但是,您应该学习正确的显式$totalTime="720"; echo $totalTime*60;echo'<br>'; echo date("H:i:s",($totalTime*60)); 语法。我认为你想要的查询更像是这样:

JOIN

注意:

  • 您不需要子查询来使用聚合。
  • 最好在SELECT DC2.county, SUM(DC2.cnt) AS nav_county FROM darwincore2 DC2 JOIN (SELECT COUNT(*) as cnt, county FROM darwincore2 WHERE darwincore2.dataeier ILIKE '%nngg%' GROUP BY county ) DC2DIST ON DC2.county = DC2DIST.county WHERE DC2.country ILIKE '%norway%’ GROUP BY DC2.county ORDER BY nav_county DESC LIMIT 10; 子句中为子查询命名列。
  • 您可能希望FROM在外部查询中而不是SUM()
  • 使用明确的COUNT()语法。