我的桌子上有SELLERS(Seller_ID, Country, Month, Sales)
。我想写一个查询以提取总销售额,发生最低销售额的月份和发生最高销售额的月份(按国家/地区)。
更新:
样本数据:
预期输出:
谢谢
答案 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
的销售额,然后找出哪个月份具有MIN
和MAX
的价值(按月和国家/地区):
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;