-1

I already provide sql fiddle with schema and sample data.

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

If I would like to know how many province and how many cities in Thailand.

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

I guess that it need to use multiple COUNT(*) but I dont know how to use it.

Anybody know please suggest solution?

4
  • What have you tried? Commented Feb 6, 2013 at 17:55
  • possible duplicate of SQL Query to Count() multiple tables Commented Feb 6, 2013 at 17:57
  • Your sqlfiddle is for MySQL, while your question is tagged PostgreSQL. And @ithcy proposes an Oracle question as duplicate (which isn't a duplicate at all). Anybody needs some coffee maybe?! Commented Feb 6, 2013 at 18:31
  • @ErwinBrandstetter haha, yes! I selected the wrong dupe. Unfortunately I can't rescind or re-cast my close vote. Commented Feb 6, 2013 at 19:05

3 Answers 3

1

You need to use GROUP BY and COUNT:

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

Good luck.

Sign up to request clarification or add additional context in comments.

3 Comments

It is not right (sqlfiddle.com/#!2/e9d22/15/0) No. of Province should be two.
@AtomSkaaskaHic -- Nope -- in your data, province only has 1 record for country id 1 :) The 2nd record is pointing at country id 2. Make sense?
@AtomSkaaskaHic -- No worries, glad we could help!
1

Try this:

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

1 Comment

I try your fiddle but it not right. No. of province should be 2 and cities should be 3.
0

It's probably faster to count cities per province before joining to province:

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

-> sqlfiddle for PostgreSQL(!)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.