每个国家每月的总销售额

时间:2018-11-18 05:45:03

标签: mysql sql oracle group-by

我的桌子上有SELLERS(Seller_ID, Country, Month, Sales)。我想写一个查询以提取总销售额,发生最低销售额的月份和发生最高销售额的月份(按国家/地区)。

更新

样本数据:

enter image description here

预期输出:

enter image description here

谢谢

2 个答案:

答案 0 :(得分:1)

尝试此查询:

SELECT SELLER_ID,
       COUNTRY,
       SUM(Sales) AS TOTAL_SALES,
       (SELECT Month FROM SELLERS WHERE Sales = (SELECT MIN(Sales) from SELLERS WHERE Country = Outer_Table.Country) LIMIT 1) AS MONTH_MIN,
       (SELECT Month FROM SELLERS WHERE Sales = (SELECT MAX(Sales) from SELLERS WHERE Country = Outer_Table.Country) LIMIT 1) AS MONTH_MAX
FROM SELLERS AS Outer_Table
GROUP BY Outer_Table.Country
ORDER BY Outer_Table.Seller_ID

您可以将HERE与您发布的数据一起尝试。

答案 1 :(得分:0)

像这样?首先计算SUM的销售额,然后找出哪个月份具有MINMAX的价值(按月和国家/地区):

with ss as
  (select country, 
          month, 
          sum(sales) sum_sales
   from sellers
   group by country, month
  )
select country, 
       month, 
       min(sum_sales) min_sales, 
       max(sum_sales) max_sales
from ss
group by country, month
order by country, month;