You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按product_id、年份、月份分组查询每日最高销售额

问题描述

我有一张存储销售数据的表sales,结构及数据如下:

idproduct_idorderdateamount
1p120 Oct 2021 12:13:03 -070010
2p121 Oct 2021 12:13:03 -070010
3p121 Oct 2021 12:13:03 -070060
4p220 Nov 2022 01:13:03 -070080
5p221 Oct 2022 12:13:03 -070010
6p221 Oct 2022 12:13:03 -070090

我需要编写SQL查询,返回每个(product_id、年份、月份)组合对应的单日最高销售总额。目前我已经能查询出每个产品每日的销售总额:

select product_id, date(orderdate) date, sum(amount) daily_total
from sales
group by 1, 2 

但不知道如何进一步获取每个(product_id、年份、月份)维度下的单日最大值,预期输出如下:

product_idyearmonthamount
p120211070
p220221180
p2202210100
解决方案

方法一:子查询+分组聚合(兼容性强)

先通过子计算出每个产品的每日销售总额,再基于产品、年份、月份分组,取每组内的单日总额最大值:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 04:46:47