 select iq.ev_count, iq.cl_count, iq.sl_count, iq.se_sgrp, iq.se_sgtm, iq.se_tsno, iq.td_test, iq.pr_name, iq.jd_name, iq.pl_name, iq.pd_name, iq.td_name, iq.se_val 
 from ( 
 select 
       se.f_sgrp se_sgrp, 
       se.f_sgtm se_sgtm, 
       se.f_tsno se_tsno, 
       se.f_val se_val, 
       pr.f_name pr_name, 
       jd.f_name jd_name, 
       pl.f_name pl_name, 
       pd.f_name pd_name, 
       td.f_test td_test, 
       td.f_name td_name, 
       (select count(cl.f_part) 
       from [spcepiworld].[dbo].[ctrl_lim] cl 
       where cl.f_part = pd.f_part 
         and cl.f_test = td.f_test 
       ) cl_count, 
       (select count(sl.f_part) 
       from [spcepiworld].[dbo].[spec_lim] sl 
       where sl.f_part = pd.f_part 
         and sl.f_test = td.f_test 
       ) sl_count, 
       (select count(ev.f_evnt) 
       from [spcepiworld].[dbo].[evnt_inf] ev 
       where ev.f_prcs = pr.f_prcs 
         and ev.f_part = pd.f_part 
         and ev.f_sgtm = se.f_sgtm 
       ) ev_count 
 from [spcepiworld].[dbo].[sgrp_ext] se 
 join [spcepiworld].[dbo].[prcs_dat] pr 
   on se.f_prcs = pr.f_prcs 
 join [spcepiworld].[dbo].[job_dat] jd 
   on se.f_job = jd.f_job 
 join [spcepiworld].[dbo].[part_lot] pl 
   on se.f_lot = pl.f_lot 
 join [spcepiworld].[dbo].[part_dat] pd 
   on se.f_part = pd.f_part 
 join [spcepiworld].[dbo].[test_dat] td  
   on se.f_test = td.f_test 
 where se.f_flag = 0 
   and se.f_sgrp = 1677273357  
   and pr.f_name = '61' 
   and pd.f_name = '5012' 
   and jd.f_name = 'CDE5' 
   and pl.f_name = '575908' 
   and dateadd(HH, -7, (dateadd(SS, convert(bigint, se.f_sgtm), '19700101'))) = '2023-02-24 15:15:00' 
 ) as iq 
 order by iq.ev_count desc, iq.cl_count desc, iq.sl_count desc, iq.se_sgrp, iq.se_tsno, iq.td_test 
   for json path 
