It looks like you are pivoting, similar to Pivoting in Pig. But you already have a bag of tuples. Doing inner join will be costly, as it will cause extra Map Reduce Jobs. To do it fast you need filtering within nested foreach. Modified code will look something like:
inpt = load '..../pig/bag_pivot.txt' as (id : int, b:bag{tuple:(id : int, count : int, key : chararray)});
result = foreach inpt {
col1 = filter b by key == 'a';
col2 = filter b by key == 'b';
generate id, flatten(col1.count) as a, flatten(col2.count) as b;
};
Sample input data:
1001 {(1001,20,a),(1001,30,b)}
1002 {(1002,40,a),(1001,50,b)}
Output:
(1001,20,30)
(1002,40,50)