sereSeré breve, necesito sacar los ultimos 20 registros, y una vez los obtenga sacar un promedio, eso dependiendo de la fecha en que estoy parado, hasta el momento tengo este query en sql server: IF OBJECT_ID('tempdb..#V_ECP_ORG_COMPLETION_FORMA') IS NOT NULL DROP TABLE #V_ECP_ORG_COMPLETION_FORMA;
SELECT A.* INTO #V_ECP_ORG_COMPLETION_FORMA FROM [V_ECP_ORG_COMPLETION_FORMAS ] A WHERE A.ORG_UNIT6_NAME = @Campo_Contrato AND A.COMPLETION_NAME = @Completion;
;WITH BOLLIGER AS ( SELECT ROW_NUMBER() OVER (ORDER BY B.START_DATETIME ASC) AS CONTADOR, A.COMPLETION_NAME AS SARTA, B.START_DATETIME AS FECHA, CAST(B.BSW_VOL_FRAC * 100 AS NUMERIC (11,3)) AS BSW, B.VALID_TEST AS [VALIDA PRUEBA], B.OIL_VOL_RATE AS VOLUMEN FROM #V_ECP_ORG_COMPLETION_FORMA A INNER JOIN VT_WELL_TEST_RAW_es_CO B ON A.ITEM_ID = B.ITEM_ID WHERE B.START_DATETIME >= (SELECT DATEADD(d,-365,GETDATE())) --order by B.START_DATETIME OFFSET 0 ROWS FETCH NEXT (SELECT CAST(CEILING(COUNT(*) * .4) AS INT) FROM BOLLIGER) ROWS ONLY )
IF OBJECT_ID('tempdb..#V_ECP_ORG_COMPLETION_FORMA') IS NOT NULL
DROP TABLE #V_ECP_ORG_COMPLETION_FORMA;
SELECT A.* INTO #V_ECP_ORG_COMPLETION_FORMA FROM [V_ECP_ORG_COMPLETION_FORMAS ] A
WHERE A.ORG_UNIT6_NAME = @Campo_Contrato
AND A.COMPLETION_NAME = @Completion;
;WITH BOLLIGER AS (
SELECT
ROW_NUMBER() OVER (ORDER BY B.START_DATETIME ASC) AS CONTADOR,
A.COMPLETION_NAME AS SARTA,
B.START_DATETIME AS FECHA,
CAST(B.BSW_VOL_FRAC * 100 AS NUMERIC (11,3)) AS BSW,
B.VALID_TEST AS [VALIDA PRUEBA],
B.OIL_VOL_RATE AS VOLUMEN
FROM #V_ECP_ORG_COMPLETION_FORMA A INNER JOIN VT_WELL_TEST_RAW_es_CO B ON A.ITEM_ID = B.ITEM_ID
WHERE B.START_DATETIME >= (SELECT DATEADD(d,-365,GETDATE()))
--order by B.START_DATETIME OFFSET 0 ROWS FETCH NEXT (SELECT CAST(CEILING(COUNT(*) * .4) AS INT) FROM BOLLIGER) ROWS ONLY
)
SELECT
A.CONTADOR,
-- CASE WHEN A.CONTADOR = 21 THEN (ROW_NUMBER() OVER (ORDER BY A.FECHA ASC)) END AS CONTADOR2,
A.SARTA,
A.FECHA,
A.BSW,
A.VOLUMEN
--,CAST((
-- SELECT AVG(B.BSW)
-- FROM BOLLIGER B
-- WHERE B.FECHA < A.FECHA
-- --and B.CONTADOR <= 20
-- --HAVING (ROW_NUMBER() OVER (ORDER BY B.FECHA ASC)) <= 20
--) AS NUMERIC (11,3)) PROMEDIO
FROM BOLLIGER A
ORDER BY A.SARTA, A.FECHA ASC
lo que esta comentariado pensecomentado pensé que me serviaservía pero no, pues tiene en cuenta todos los promedios, mas no los ultimosúltimos 20, muchas gracias por la ayuda