如何按product_id、年份、月份分组查询每日最高销售额
问题描述
我有一张存储销售数据的表sales,结构及数据如下:
| id | product_id | orderdate | amount |
|---|---|---|---|
| 1 | p1 | 20 Oct 2021 12:13:03 -0700 | 10 |
| 2 | p1 | 21 Oct 2021 12:13:03 -0700 | 10 |
| 3 | p1 | 21 Oct 2021 12:13:03 -0700 | 60 |
| 4 | p2 | 20 Nov 2022 01:13:03 -0700 | 80 |
| 5 | p2 | 21 Oct 2022 12:13:03 -0700 | 10 |
| 6 | p2 | 21 Oct 2022 12:13:03 -0700 | 90 |
我需要编写SQL查询,返回每个(product_id、年份、月份)组合对应的单日最高销售总额。目前我已经能查询出每个产品每日的销售总额:
select product_id, date(orderdate) date, sum(amount) daily_total from sales group by 1, 2
但不知道如何进一步获取每个(product_id、年份、月份)维度下的单日最大值,预期输出如下:
| product_id | year | month | amount |
|---|---|---|---|
| p1 | 2021 | 10 | 70 |
| p2 | 2022 | 11 | 80 |
| p2 | 2022 | 10 | 100 |
解决方案
方法一:子查询+分组聚合(兼容性强)
先通过子计算出每个产品的每日销售总额,再基于产品、年份、月份分组,取每组内的单日总额最大值:
select product_id, extract(year from date(orderdate)) as year, extract(month from date(orderdate)) as month, max(daily_total) as amount from ( select product_id, date(orderdate) as order_date, sum(amount) as daily_total from sales group by product_id, order_date ) as daily_sales group by product_id, year, month order by product_id, year, month;
方法二:窗口函数(灵活拓展)
适用于支持窗口函数的SQL方言(如PostgreSQL、MySQL 8+、SQL Server等),如果需要同时查看最高总额对应的具体日期,这种方法更易调整:
with daily_sales as ( select product_id, date(orderdate) as order_date, sum(amount) as daily_total, extract(year from date(orderdate)) as year, extract(month from date(orderdate)) as month from sales group by product_id, order_date ) select distinct product_id, year, month, max(daily_total) over (partition by product_id, year, month) as amount from daily_sales order by product_id, year, month;
注意事项
不同SQL方言的日期提取语法略有差异:
- MySQL可替换为
year(date(orderdate))和month(date(orderdate)) - SQL Server可替换为
DATEPART(year, date(orderdate))和DATEPART(month, date(orderdate))
内容的提问来源于stack exchange,提问作者Ankit
相关产品推荐
相关产品推荐

