我需要使用相同的查询 with 为每个国家/地区输出创建 colmun多少个城市

问题描述

WITH city_count_per_country AS
  (SELECT
    country_name,count(city_id) AS count
  
  FROM dim_city
   
  GROUP BY 1),average_count AS
   (SELECT
    avg(count) AS avg
  FROM city_count_per_country)

SELECT country_name
FROM city_count_per_country,average_count
WHERE count > average_count.avg

结果:

+-------------------+
| country_name  |   |
+-------------------+ |
+-------------------+
| Germany        |  |
+-------------------+
| France         |  |
+-------------------+
| Colombia       |  |
+-------------------+
| Russia         |  |
+-------------------+
| Australia      |  |
+-------------------+
| United States  |  |
+-------------------+
| Argentina      |  |
+-------------------+
| Brazil         |  |
+-------------------+
| Mexico         |  |
+-------------------+
| Spain          |  |
+-------------------+
| Canada         |  |
+-------------------+
| United Kingdom |  |
+-------------------+
| India          |  |
+-------------------+

解决方法

如果您想显示一个国家/地区的城市数量,您可以在最终输出中使用 count 中的 city_count_per_country 列。使用正确的连接语法总是更好。所以我使用了内连接。 Count 是保留字,因此最好不要将其用作列名,因此我改用 country_count。请检查以下查询:

WITH city_count_per_country AS
  (SELECT
    country_name,count(city_id) AS country_count
  
  FROM dim_city
   
  GROUP BY country_name),average_count AS
   (SELECT
    avg(country_count) AS avg
  FROM city_count_per_country)

SELECT country_name,country_count
FROM city_count_per_country inner join average_count
on country_count> average_count.avg

您还可以使用窗口函数(如果您的 dbms 允许)计算同一 CTE 内的平均值。请检查查询#2。

 create table dim_city (country_name varchar(10),city_id int);
 insert into dim_city values('russia',3);
 insert into dim_city values('russia',2);
 insert into dim_city values('russia',1);
 insert into dim_city values('Germany',12);
 insert into dim_city values('Germany',10);
 insert into dim_city values('bd',20);
 insert into dim_city values('bd',21);
 insert into dim_city values('bd',22);

查询 #1:

 WITH city_count_per_country AS
       (SELECT
         country_name,count(city_id) AS country_count
       
       FROM dim_city
        
       GROUP BY country_name),average_count AS
        (SELECT
         avg(country_count) AS avg
       FROM city_count_per_country)
     
     SELECT country_name,country_count
     FROM city_count_per_country inner join average_count
     on country_count average_count.avg

输出:

country_name country_count
bd 3
俄罗斯 3

查询 #2:

 with city_count_per_country as
 (  
   SELECT
     country_name,count(city_id) AS country_count,avg(count(city_id))over() as average_country_count
   
   FROM dim_city
    
   GROUP BY country_name
 )
 select country_name,country_count from city_count_per_country
 where country_count  average_country_count
 GO

输出:

country_name country_count
bd 3
俄罗斯 3

dbhere