【问题标题】:Find the max of a sum求和的最大值
【发布时间】:2020-08-26 09:44:42
【问题描述】:

在使用 SQL 中的 summax 函数时,我需要一些帮助。

我想显示每年销售额最高的月份。

我有两张桌子

sales.orderline:
orderno - prodno - quantity - price - linetotal

sales.custorder:
orderno - custno - salesrep - orderdate 

这就是我所拥有的:

select year(orderdate) as year, month(orderdate) as month, sum(linetotal) as sales
from sales.custorder 
inner join sales.orderline on sales.custorder.orderno = sales.orderline.orderno
where year(orderdate) is not null and month(orderdate) is not null
group by month(orderdate), year(orderdate)

我的问题是,这显示了一年中每个月的总数,我不知道如何只选择每年总数最高的月份。我唯一的想法是max(sum()),这不起作用。

【问题讨论】:

    标签: sql sql-server tsql group-by greatest-n-per-group


    【解决方案1】:

    如果您的数据库支持,您可以使用窗口函数:

    select *
    from (
        select 
            year(orderdate) as yr, 
            month(orderdate) as mn, 
            sum(linetotal) as sales,
            rank() over(partition by year(orderdate) order by sum(linetotal) desc) rn
        from sales.custorder 
        inner join sales.orderline on sales.custorder.orderno = sales.orderline.orderno
        where year(orderdate) is not null and month(orderdate) is not null
        group by month(orderdate), year(orderdate)
    ) t
    where rn = 1
    order by yr
    

    请注意,rank() 允许顶部关系,如果有的话。

    无关:条件year(orderdate) is not null and month(orderdate) is not null 可以简化为orderdate is not null

    【讨论】:

      【解决方案2】:

      您可以使用row_number()。假设您一年中有两个月的销售额相同,那么您可以使用dense_rank()

      select
        year,
        month,
        sales
      from
      (
        select 
          year(orderdate) as year, 
          month(orderdate) as month, 
          sum(linetotal) as sales,
          row_numbe() over (partition by year(orderdate) order by sum(linetotal) desc) as rnk
        from sales.custorder sc
        inner join sales.orderline so
        on sc.orderno = so.orderno
        where year(orderdate) is not null 
        and month(orderdate) is not null
        group by 
          month(orderdate), 
          year(orderdate)
      ) val
      where rnk = 1
      
      order by
        year,
        month
      

      【讨论】:

        猜你喜欢
        • 2015-01-09
        • 2023-03-31
        • 2022-06-26
        • 2014-05-24
        • 1970-01-01
        • 2012-06-24
        • 1970-01-01
        • 2013-01-17
        • 2018-10-19
        相关资源
        最近更新 更多