【问题标题】:SQL query between three tables using AVG and COUNT together一起使用 AVG 和 COUNT 在三个表之间进行 SQL 查询
【发布时间】:2022-11-20 01:02:44
【问题描述】:

我遇到了这个超级复杂的 SQL 查询,我很想看看解决方案是什么。
所需要的是编写一个查询,该查询将返回所有客户多于平均数所有城市的客户。对于每个这样的城市,返回国家的名字,城市名称和客户数量.按国家名称排序结果上升.
以下是表格:

country: id, country_name  
city: id, city_name, postal_code, country_id  
customer: id, city_id, customer_name

我所能达到的最好结果是返回按城市分组的平均客户数。
有人可以输入查询吗?

【问题讨论】:

  • 更新您的问题添加适当的数据样本和预期结果
  • 您必须在 CTE/子查询中计算“所有城市的平均客户数”,然后使用表的另一个副本进行最终选择。我所能达到的最好结果是返回按城市分组的平均客户数如果结果正确,则第一步完成。

标签: mysql sql


【解决方案1】:

看起来您需要嵌套的 SELECTS 和 GROUP-BY:

SELECT
    *
FROM 
(
    /* compine first Inner-select with the second inner-select */
    SELECT 
        count(*) number_customer,
        city_name,
        country_name,
        avg_number_customer
    FROM 
        city,
        country,
        customer
        (
            /* Calculate average customer */
            SELECT 
                AVG(number_customer) avg_number_customer 
            FROM (
                /* GET number of customers for country/city */
                SELECT 
                    count(*) number_customer,
                    city_name,
                    country_name
                FROM 
                    city,
                    country,
                    customer 
                WHERE
                    city.id = customer_city_id
                    AND country.id = city_country_id
                GROUP BY
                    city_name,
                    country_name
            )
        )
    WHERE 
        city.id = customer_city_id
        AND country.id = city_country_id
    GROUP BY
        city_name,
        country_name,
        avg_number_customer
)
WHERE number_customer > avg_number_customer -- show only data, where number_customer > AVG 
;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-17
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多