sql - Alasql - 分组并取最大结果
问题描述
我有以下格式的表格:
Vendor Id Weight
AAA 1 1234
AAA 1 121
AAA 2 5182
BBB 1 311
BBB 1 9132
BBB 2 108
我需要按“供应商”和“ID”分组并总结“重量”。无论哪个“Id”具有最大“权重”,都必须分配给相应的“供应商”。在下面的示例中,供应商“AAA”的 Id“2”的最大权重为 5182,而 Id“1”的权重为 1355 (1234+121)。因此应将 ID“2”分配给供应商“AAA”。类似地,对于供应商“BBB”,必须分配 ID“1”,因为它的最大权重为 9443(311+9132),而 ID“2”的权重为“108”。
结果必须是
Vendor Id
AAA 2
BBB 1
我正在尝试在“Alasql”中实现这一点,它是 Google Apps 脚本的查询语言。
任何建议,将不胜感激。
解决方案
你可以使用窗口函数来做到这一点:
select * from (
select Vendor,id,sum(weight) summWeight, row_number() over (order by sum(weight) desc) rn
from yourtable
group by Vendor,id
) tt
where rn = 1
那么你可以这样做:
select t.*
from (
select Vendor,max(summWeight) Maxweight from (
select Vendor,id,sum(weight) summWeight
from yourtable
group by Vendor,id
) tt
group by Vendor
) tt join (
select Vendor,id,sum(weight) summWeight
from yourtable
group by Vendor,id
) t
on t.vendor = tt.vendor
and summWeight = Maxweight
推荐阅读
- javascript - InnerHTML 或 InnerText 用于按原样输出 html 标签
- excel - WScript.Shell 使 Excel 崩溃
- vue.js - 在 Jest (Vue) 中模拟 $route
- scala - Akka 调度程序:等待 Runnable 完成
- css - 如何通过平滑过渡到透明来为 CSS 渐变停止设置动画?
- shader - Metal / SceneKit Fragment Shaders - 如何避免在其他几何体上渲染?
- r - Highcharter中的Plotbands - 当x轴是日期时
- reactjs - 我可以在我的应用程序中使用 redux 什么(建议)?
- python-3.x - 使用总辐照度计算紫外线指数
- sqlite - /admin/registration/donor/ 处的 OperationalError 没有这样的表:registration_donor