mysql 同时使用AVG和COUNT在三个表之间进行SQL查询[已关闭]

b09cbbtk  于 2022-11-21  发布在  Mysql
关注(0)|答案(1)|浏览(200)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

19个小时前关门了。
Improve this question
我沿着这个超级复杂的SQL查询,我很想看看有什么解决方案。
需要编写一个查询,该查询将返回客户数量超过所有城市的平均客户数量的所有城市。对于每个这样的城市,返回国家名称、城市名称和客户数量。按国家名称升序对结果进行排序。
下表:

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

最好的我可以实现它返回的平均数的客户分组的城市。
有人可以输入查询吗?

7ivaypg9

7ivaypg91#

看起来您需要嵌套的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 
;

相关问题