找出总和的最大值

Find the max of a sum

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

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

我有2张桌子

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)

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

您可以使用 window 函数,如果您的数据库支持它们:

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

您可以使用 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