with cte1 as ( SELECT trading_day, instrument_id ,sum(volume) as sum_vol FROM public."AP_1minute_bars" group by trading_day,instrument_id ), cte2 as ( select trading_day ,max(sum_vol) as max_vol from cte1 group by trading_day ), cte3 as ( select cte1.trading_day,cte1.instrument_id,cte1.sum_vol from cte1,cte2 where cte1.sum_vol = cte2.max_vol and cte1.trading_day=cte2.trading_day ), cte4 as ( select "AP_1minute_bars".trading_day,count("AP_1minute_bars".update_time) as bar_num from "AP_1minute_bars",cte3 where cte3.instrument_id="AP_1minute_bars".instrument_id and cte3.trading_day="AP_1minute_bars".trading_day group by "AP_1minute_bars".trading_day ) select * from cte4 order by bar_num asc;