【问题标题】:Mysql query - summ total by country, region and take percentage of total (general)Mysql查询 - 按国家、地区和占总数的百分比求和(一般)
【发布时间】:2019-05-18 17:33:15
【问题描述】:

我有两张桌子 1. 地理 2. 销售

  1. 带字段的地理 国家、城市、用户 ID

  2. 带有字段的销售 用户 ID、销售额

我需要进行查询并获得带有文件的结果 country / city / sales_amount (by city) / percent of total(general) by city

如何在不加入销售表的情况下实现它? 你能帮我查询一下吗?

我只知道自己加入销售(但它不起作用)

我尝试将 Sales 加入到自身,但它不起作用

Select Geo.country, Geo.city, sum(Sales_amount), 
(sum(Sales_amount))/"t" as "percentage of general total"
From Geo
Join 
Sales
On Geo.UserId = Sales.UserId
Join
(Select userId, summ(sales_amount) as "total" from Sales) as "t" 
ON t.userId = Geo.UserId
Group by Geo.country, Geo.city

结果什么也没有(

【问题讨论】:

标签: mysql group-by percentage


【解决方案1】:

表之间的连接,然后按城市求和。
百分比可以通过每个总和除以总数来检索:

select 
  g.country, 
  g.city,
  sum(s.sales_amount) citysales,
  100.0 * sum(s.sales_amount) / (select sum(sales_amount) from sales) percentage
from geo g left join sales s
on g.userid = s.userid
group by g.country, g.city

【讨论】:

  • 也许您知道一些查询优化或其他解决方法?因为销售表太大了,当我运行查询时需要很多时间
  • 连接列的索引:geo.userid 和 sales.userid 会有所帮助(如果它们还没有的话)。此外,如果您的 Mysql 版本是 8.0,您可以使用 CTE 代替 (select sum(sales_amount) from sales),尽管我相信它已经优化,因此只评估一次。
猜你喜欢
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 2011-12-20
相关资源
最近更新 更多