首页 > 解决方案 > 求和的最大值

问题描述

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

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

我有 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)

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

标签: sqlsql-servertsqlgroup-bygreatest-n-per-group

解决方案


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

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


推荐阅读