【问题标题】:Find total count and average based of values from another table根据另一个表中的值查找总计数和平均值
【发布时间】:2020-03-12 20:38:45
【问题描述】:

在Mysql中:

我在表格中有客户姓名(主键)、城市和金额:

表格城市:

customer     location        amount

Cust1        New York, USA   200
Cust2        New York, USA   300
Cust3        Chicago, USA    100
Cust4        Paris, France   400
Cust5        Nice, France    500
Cust6        Milan, Italy    600
Cust7        Mumbai, India   0

此表中位置名称的格式为:

<city>, <country>

同:

<city><comma><space><country>

表格国家(主键):

Name

USA
France
Italy
India
Thailand

我想知道每个国家有多少个城市,以及每个国家的平均数量。喜欢:

Country      Count     Average

USA           3        200      // (200 + 300 + 100) / 3
France        2        450      // (400 + 500) / 2
Italy         1        600      // (600) / 1
India         1        0        // (0) / 1
Thailand      0        0        //  0

所以,我的查询是:

SELECT t1.name Country, count(distinct t2.location) Count
FROM Country t1 LEFT JOIN Cities t2 
ON t2.location LIKE concat('%, ', t1.name)
GROUP BY t1.name ORDER BY Count DESC

但它不给出平均数据,它只给出国家名称和计数

【问题讨论】:

  • 客户名称不是可持续的主键
  • 你好,只是为了代表,我想说城市可以重复,我想统计一下全国的平均值。

标签: mysql sql join group-by count


【解决方案1】:

这是一种方法:

select co.name, count(*) cnt, coalesce(avg(amount), 0) avg
from countries co
left join cities ci 
    on ci.location like concat('%, ', co.name)
group by co.name
order by co.name

请注意,您存储数据的方式效率低下。你应该:

  • 在两个不同的列中将城市名称与国家/地区分开

  • 在国家表中有一个主键,并在城市表中引用它

对于您的数据集,这将是:

国家

id | name
-- | ---------
 1 | USA
 2 | France
 3 | Italy
 4 | India
 5 | Thailand

城市

id | customer | location | country_id | amount
-- | -------- | -------- | ---------- | ------
 1 | Cust1    | New York |          1 |    200
 2 | Cust2    | New York |          1 |    300
 3 | Cust3    | Chicago  |          1 |    100
 4 | Cust4    | Paris    |          2 |    400
 5 | Cust5    | Nice     |          2 |    500
 6 | Cust6    | Milan    |          3 |    600
 7 | Cust7    | Mumbai   |          4 |      0

【讨论】:

  • 是的,我一定会把城市名称和国家分开在两个不同的列中。感谢您的提示。
猜你喜欢
  • 2020-06-24
  • 1970-01-01
  • 2021-01-26
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多