我在使用SQL中的sum
和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())
,它不起作用。
您可以使用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
如果数据库支持,则可以使用窗口函数:
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
。