@@ -241,32 +241,46 @@ def run_grouped_timeseries_query(
241241 col .internal_name : col .public_alias for col in groupbys_resolved
242242 }
243243
244- # Process results into flat list format
245- results : list [dict [str , Any ]] = []
244+ # Group timeseries by their groupby attributes, then merge aggregates
245+ # This handles multiple y_axes correctly by merging them into the same rows
246+ results_by_key : dict [tuple , dict [int , dict [str , Any ]]] = {}
246247
247248 for timeseries in rpc_response .result_timeseries :
248249 # Extract groupby values using public aliases
249250 groupby_values : dict [str , Any ] = {}
250251 for internal_name , value in timeseries .group_by_attributes .items ():
251252 public_alias = groupby_internal_to_public .get (internal_name )
252253 if public_alias :
253- # Process the value (handle type conversions)
254254 groupby_values [public_alias ] = process_value (value )
255255
256- # Convert each bucket to a flat row
256+ # Create a hashable key from groupby values
257+ groupby_key = tuple (sorted (groupby_values .items ()))
258+
259+ if groupby_key not in results_by_key :
260+ results_by_key [groupby_key ] = {}
261+
262+ # Merge each bucket's aggregate value into the result
257263 for i , bucket in enumerate (timeseries .buckets ):
258- row : dict [str , Any ] = {
259- ** groupby_values ,
260- "time" : bucket .seconds ,
261- }
264+ time_key = bucket .seconds
262265
263- # Add aggregate values
266+ if time_key not in results_by_key [groupby_key ]:
267+ results_by_key [groupby_key ][time_key ] = {
268+ ** groupby_values ,
269+ "time" : time_key ,
270+ }
271+
272+ # Add/merge aggregate value
264273 if i < len (timeseries .data_points ):
265274 data_point = timeseries .data_points [i ]
266- row [timeseries .label ] = process_value (data_point .data )
275+ results_by_key [groupby_key ][time_key ][timeseries .label ] = process_value (
276+ data_point .data
277+ )
267278 else :
268- row [timeseries .label ] = 0
279+ results_by_key [ groupby_key ][ time_key ] [timeseries .label ] = 0
269280
270- results .append (row )
281+ # Flatten the nested dict into a list
282+ results : list [dict [str , Any ]] = []
283+ for time_dict in results_by_key .values ():
284+ results .extend (time_dict .values ())
271285
272286 return results
0 commit comments