0

我有这三张桌子

CREATE TABLE "Countries"
(
  name text NOT NULL,
  pop integer,
  CONSTRAINT country PRIMARY KEY (name),
  CONSTRAINT pop_check CHECK (pop > 0)
)

CREATE TABLE "Cities"
( name text NOT NULL, pop integer,
  country_name text,
  CONSTRAINT "City_ref" PRIMARY KEY (name),
  CONSTRAINT country_ref FOREIGN KEY (country_name)
      REFERENCES "db1001002_Countries" (name) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT "Population" CHECK (pop > 0)
);

CREATE TABLE " Company"
(
  "City_name" text NOT NULL,
  "Company_Name" text NOT NULL,
  no_of_employee integer,
  CONSTRAINT "City_company" PRIMARY KEY ("City_name", "Company_Name"),
  CONSTRAINT city_ref FOREIGN KEY ("City_name")
      REFERENCES "Cities" (name) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT employee_check CHECK (no_of_employee > 0)
)

我的问题是我想使用格式的嵌套查询

select field(s) from table(s)
where field(s) in (select field(s) from table(s) condition)
group by field(s) 

获取包含字段的新表

country, min_pop, max_pop, average_pop 
for cities with pop > 500000

我尝试编写一些查询,但在您的子查询中不断收到太多字段的错误。我正在使用 postgresql 9.3。

当我使用这个查询时,我得到了一些结果。

SELECT country_name, min_pop, max_pop, avg_popo
  FROM (SELECT country_name, min(pop),max(pop),avg(pop)
  FROM
  "Cities"
  GROUP BY country_name)
  AS popcal(country_name,min_pop, max_pop, avg_popo)
  WHERE min_pop>500000

有没有办法以这种格式编写查询

select field(s) from table(s)
where field(s) in (select field(s) from table(s) condition)
group by field(s) 

?

4

2 回答 2

1

我不确定我是否理解这个问题,但如果您需要过滤第一个国家,其中至少有一个城市人口超过 50,000,您可以通过这种方式使用子查询:

SELECT country_name, MIN(pop) AS min_pop, MAX(pop) AS max_pop, avg(pop) AS avg_pop
FROM "Cities"
  WHERE country_name IN (
    SELECT DISTINCT country_name
    FROM
      "Cities"
    WHERE pop>500000)
GROUP BY country_name

子查询返回您需要的国家/地区,然后您可以将其用于聚合查询。

于 2013-10-25T13:26:44.130 回答
0

请编辑原始问题。鉴于您的评论,您问的是一个完全不同的问题...... AndreaBoc 的答案是正确的。

于 2013-10-25T12:48:59.087 回答