SELECT id_hr, SFR_ID_CAT_SOC_SEC, debut, fin, TOT, TA, BASE, SS_TOT, SS_TrA
FROM (select SFR_ID_HR, min(SFR_DT_START) debut, max(SFR_DT_END) fin, sum(SFR_S40_G28_05_029_001) SS_TOT, sum(SFR_S40_G28_05_030_001) SS_TrA from M4SFR_N4DS_S40_G28_05 where   CONVERT(char(4),  SFR_DT_START,126) = '2011' and SFR_ID_SCENARIO like 'DS11' group by SFR_ID_HR
) DA,
(SELECT P2.SCO_ID_HR id_hr, SFR_ID_CAT_SOC_SEC, sum(SFR_BAS_SS_FNAL_TA) TA,  sum(SFR_BAS_SS_MAL_N_E) TOT, sum(SFR_AMT_SS_MONTH) BASE
 FROM M4SCO_AC_HR_PERIO2 P2, M4SFR_AC_HR_PERIOD SP,  M4SCO_AC_HR_PERIOD P1 WHERE P2.SCO_DT_PAY = SP.SCO_DT_PAY AND P2.SCO_ID_HR = SP.SCO_ID_HR AND P2.SCO_DT_ALLOC = SP.SCO_DT_ALLOC AND P2.SCO_OR_HR_PERIOD = SP.SCO_OR_HR_PERIOD and P2.SCO_DT_START_SLICE = SP.SCO_DT_START_SLICE AND P2.SCO_DT_PAY = P1.SCO_DT_PAY AND P2.SCO_ID_HR = P1.SCO_ID_HR AND P2.SCO_DT_ALLOC = P1.SCO_DT_ALLOC AND P2.SCO_OR_HR_PERIOD = P1.SCO_OR_HR_PERIOD and P2.SCO_DT_START_SLICE = P1.SCO_DT_START_SLICE AND  
CONVERT(char(4),  SP.SCO_DT_PAY,126) = '2011' and SCO_ID_LEG_ENT = 'DS' group by P2.SCO_ID_HR, SFR_ID_CAT_SOC_SEC
) RP
where SFR_ID_HR = id_hr and SFR_ID_CAT_SOC_SEC '31'
and (abs(TOT - SS_TOT) > 2 and SFR_ID_CAT_SOC_SEC '02' or abs(TA - SS_TrA) > 2 or abs(TA - SS_TOT) > 2 and SFR_ID_CAT_SOC_SEC = '02')
order by 1, 3