SQL在查询中遇到多次计数问题

时间:2013-02-06 17:52:42

标签: sql postgresql

我已经提供了sql fiddle with schema和sample data。

http://sqlfiddle.com/#!2/e9d22/7/0

如果我想知道泰国有多少个省和多少个城市。

Country Name | No. Provinces | No. Cities
  Thailand   |   77          |  1234

我猜它需要使用多个COUNT(*),但我不知道如何使用它。

有人知道请提出解决方案吗?

3 个答案:

答案 0 :(得分:1)

您需要使用GROUP BYCOUNT

SELECT c.name, count(distinct p.id) provincecoutn, count(distinct city.id) citycount
FROM country c
  LEFT JOIN province p on c.id = p.country_id
  LEFT JOIN City on p.id = city.province_id
GROUP BY c.name
祝你好运。

答案 1 :(得分:1)

试试这个:

SELECT
    C.Name, COUNT(DISTINCT P.Id) NoProvance, COUNT(CC.Id) NoCities
FROM country C
    JOIN province P
        ON C.Id = P.COUNTRY_ID
    JOIN city CC
        ON P.Id = CC.province_id
WHERE C.Name = 'Thailand'
GROUP BY C.Name

<强> SQL FIDDLE DEMO

答案 2 :(得分:0)

在加入省之前计算每个省的城市可能会更快:

SELECT c.name          AS "Country Name"
      ,count(p.id)     AS "No. Provinces"
      ,sum(ci.city_ct) AS "No. Cities" 
FROM   country       c
LEFT   JOIN province p ON p.country_id = c.id
LEFT   JOIN (
   SELECT province_id, count(*) AS city_ct FROM city GROUP BY 1
   ) ci ON ci.province_id = p.id
GROUP  BY 1
PostgreSQL的

-> sqlfiddle(!)