(@P1 numeric(10),@P2 numeric(10),@P3 numeric(10),@P4 datetime2(3))
INSERT INTO #tt66 WITH(TABLOCK) (_Q_001_F_000_TYPE, _Q_001_F_000_RTRef, _Q_001_F_000_RRRef) 
SELECT
T1.Fld44327_TYPE,
T1.Fld44327_RTRef,
T1.Fld44327_RRRef
FROM (SELECT
T6._Fld44327_TYPE AS Fld44327_TYPE,
T6._Fld44327_RTRef AS Fld44327_RTRef,
T6._Fld44327_RRRef AS Fld44327_RRRef,
T6._Fld44329 AS Fld44329_
FROM (SELECT
T3.Fld44327_TYPE AS Fld44327_TYPE,
T3.Fld44327_RTRef AS Fld44327_RTRef,
T3.Fld44327_RRRef AS Fld44327_RRRef,
T3.Fld44328RRef AS Fld44328RRef,
T3.Fld44329_ AS Fld44329_,
T3.Fld44330_ AS Fld44330_,
T3.Fld44331RRef AS Fld44331RRef,
T3.Fld44332RRef AS Fld44332RRef,
T3.MAXPERIOD_ AS MAXPERIOD_,
SUBSTRING(MAX(T5._RecorderTRef + T5._RecorderRRef),1,4) AS MAXRECORDERTRef,
SUBSTRING(MAX(T5._RecorderTRef + T5._RecorderRRef),5,16) AS MAXRECORDERRRef
FROM (SELECT
T4._Fld44327_TYPE AS Fld44327_TYPE,
T4._Fld44327_RTRef AS Fld44327_RTRef,
T4._Fld44327_RRRef AS Fld44327_RRRef,
T4._Fld44328RRef AS Fld44328RRef,
T4._Fld44329 AS Fld44329_,
T4._Fld44330 AS Fld44330_,
T4._Fld44331RRef AS Fld44331RRef,
T4._Fld44332RRef AS Fld44332RRef,
MAX(T4._Period) AS MAXPERIOD_
FROM dbo._InfoRg44326 T4
WHERE ((T4._Fld2507 = @P1)) AND (T4._Active = 0x01)
GROUP BY T4._Fld44327_TYPE,
T4._Fld44327_RTRef,
T4._Fld44327_RRRef,
T4._Fld44328RRef,
T4._Fld44329,
T4._Fld44330,
T4._Fld44331RRef,
T4._Fld44332RRef) T3
INNER JOIN dbo._InfoRg44326 T5
ON T3.Fld44327_TYPE = T5._Fld44327_TYPE AND T3.Fld44327_RTRef = T5._Fld44327_RTRef AND T3.Fld44327_RRRef = T5._Fld44327_RRRef AND T3.Fld44328RRef = T5._Fld44328RRef AND T3.Fld44329_ = T5._Fld44329 AND T3.Fld44330_ = T5._Fld44330 AND T3.Fld44331RRef = T5._Fld44331RRef AND T3.Fld44332RRef = T5._Fld44332RRef AND T3.MAXPERIOD_ = T5._Period
WHERE ((T5._Fld2507 = @P2)) AND (T5._Active = 0x01)
GROUP BY T3.Fld44327_TYPE,
T3.Fld44327_RTRef,
T3.Fld44327_RRRef,
T3.Fld44328RRef,
T3.Fld44329_,
T3.Fld44330_,
T3.Fld44331RRef,
T3.Fld44332RRef,
T3.MAXPERIOD_) T2
INNER JOIN dbo._InfoRg44326 T6
ON T2.Fld44327_TYPE = T6._Fld44327_TYPE AND T2.Fld44327_RTRef = T6._Fld44327_RTRef AND T2.Fld44327_RRRef = T6._Fld44327_RRRef AND T2.Fld44328RRef = T6._Fld44328RRef AND T2.Fld44329_ = T6._Fld44329 AND T2.Fld44330_ = T6._Fld44330 AND T2.Fld44331RRef = T6._Fld44331RRef AND T2.Fld44332RRef = T6._Fld44332RRef AND T2.MAXPERIOD_ = T6._Period AND T2.MAXRECORDERTRef = T6._RecorderTRef AND T2.MAXRECORDERRRef = T6._RecorderRRef
WHERE (T6._Fld2507 = @P3)) T1
WHERE (T1.Fld44327_TYPE = 0x08 AND T1.Fld44327_RTRef = 0x000004CB) AND EXISTS(SELECT
1
FROM #tt62 T7 WITH(NOLOCK)
WHERE (T1.Fld44327_TYPE = T7._Q_001_F_000_TYPE AND T1.Fld44327_RTRef = T7._Q_001_F_000_RTRef AND T1.Fld44327_RRRef = T7._Q_001_F_000_RRRef)) AND (T1.Fld44329_ <= @P4)
GROUP BY T1.Fld44327_TYPE,
T1.Fld44327_RTRef,
T1.Fld44327_RRRef

