sql - 求和的最大值
问题描述
在使用SQL中的sum
and函数时,我需要一些帮助。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())
哪个行不通。
解决方案
如果您的数据库支持,您可以使用窗口函数:
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
。
推荐阅读
- php - 如何将自定义参数/属性从树枝模板传递到自定义表单字段?
- javascript - 如何从开发者控制台访问“exerciseObject”?
- python - 我正在尝试解密我的填充但只收到 1 个字符
- javascript - React:useEffect 中的昂贵计算阻塞了渲染
- sql - 时间序列数据的孤岛和缺口问题
- java - 2020-12-21T13:00:00.000+0000 的 SimpleDateFormat 掩码
- logging - 如何在 Kubernetes 集群上使用 EFK 架构访问 LoadBalancer 日志文件
- php - 我正在尝试向我的 PHP 脚本添加分页,但它不起作用并且总是显示 HTTP 错误 500
- c# - 通过 SSH 隧道连接到 .Net Core 中的 AWS DocumentDb
- python - 将调试器附加到在容器中运行的 Azure Function App