首页 > 解决方案 > 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 脚本的查询语言。

任何建议,将不胜感激。

标签: sqlgroup-byalasql

解决方案


你可以使用窗口函数来做到这一点:

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

推荐阅读