0

I have a table in the below format:

Vendor Id  Weight
 AAA   1   1234
 AAA   1   121
 AAA   2   5182
 BBB   1   311 
 BBB   1   9132
 BBB   2   108

I need to group by "Vendor" and "Id" and sum the "Weight". Whichever "Id" has the maximum "Weight" has to be assigned to the corresponding "Vendor". In the below example, Id "2" of Vendor "AAA" has a maximum weight of 5182 compared to the Id "1" whose weight is 1355 (1234+121). Hence Id "2" should be assigned to vendor "AAA". Similarly for Vendor "BBB", Id "1" has to be assigned as it has the maximum weight 9443 (311+9132) compared to Id "2" whose weight is "108".

Result has to be

Vendor Id
AAA    2
BBB    1

I am trying to implement this in "Alasql" which is the query language for Google Apps Script.

Any suggestions would be appreciated.

user3447653
  • 3,968
  • 12
  • 58
  • 100

1 Answers1

0

you can use window functions to do that:

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

then this is how you can do it:

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
eshirvana
  • 23,227
  • 3
  • 22
  • 38