Search code examples
sqlderby

How to count rows which are divided into other variables as a whole?


This way i get one river and all provinces it flows through are counted:

SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER

This way i get the same river multiple times and it counts for every country the provinces the river flows thorugh together:

SELECT Geo_River.RIVER, COUNT(Geo_River.COUNTRY)
FROM Geo_River
GROUP BY Geo_River.RIVER, Geo_River.COUNTRY

I want to count the countries the river flows through but some country are divided into different provinces. If so the country should be count as one and not by number of provinces.

CREATE TABLE Country
(Name VARCHAR(40) NOT NULL UNIQUE,
 Code VARCHAR(4) CONSTRAINT CountryKey PRIMARY KEY,
 Capital VARCHAR(40),
 Province VARCHAR(40),
 Area INTEGER CONSTRAINT CountryArea
   CHECK (Area >= 0),
 Population INTEGER CONSTRAINT CountryPop
   CHECK (Population >= 0));
CREATE TABLE geo_River
(River VARCHAR(40) , 
 Country VARCHAR(4) ,
 Province VARCHAR(40) ,
 CONSTRAINT GRiverKey PRIMARY KEY (Province ,Country, River) );

Solution

  • You need to use distinct within count. Also if you are not doing a join then no need to provide table name before columns.

    SELECT 
      RIVER, 
      COUNT(distinct COUNTRY)
    FROM Geo_River
    GROUP BY 
      RIVER