 select case when iq.sl_loos is null then 0 else iq.sl_loos end + 
        case when iq.sl_uoos is null then 0 else iq.sl_uoos end + 
        iq.ev_count as iq_sum, 
        iq.sl_aflag, 
        iq.sl_loos, 
        iq.sl_uoos, 
        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, 
        iq.sl_eflag, 
        iq.sl_scal, 
        iq.sl_sls, 
        iq.sl_usl 
 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, 
       sl.f_eflag sl_eflag, 
       sl.f_aflag sl_aflag, 
       sl.f_scal sl_scal, 
       sl.f_lsl sl_sls, 
       sl.f_usl sl_usl, 
       case when sl.f_aflag is null or sl.f_aflag = 0 then null else 
         case when round(se.f_val, sl.F_scal, 1) < sl.f_lsl then 1 else 0 end 
       end as sl_loos, 
       case when sl.f_aflag is null or sl.f_aflag = 0 then null else 
         case when round(se.f_val, sl.F_scal, 1) > sl.f_usl then 1 else 0 end 
       end as sl_uoos, 
       (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 
 left join [spcepiworld].[dbo].[spec_lim] sl 
   on se.f_part = sl.f_part 
  and se.f_test = sl.f_test 
 where se.f_flag = 0 
   and (sl.f_prcs is null or se.f_prcs = sl.f_prcs or sl.f_prcs = 0) 
   and se.f_sgrp = 1698497987  
   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.sl_loos + iq.sl_uoos + iq.ev_count desc, 
          iq.sl_aflag desc, 
          iq.se_sgrp, 
          iq.se_tsno, 
          iq.td_test 
   for json path 
