Monday, May 21, 2018

Obtain the count of total rows from SQL query bounded by rownum




Below query i used in a  project where  TOTAL count was obtained  even when Query is bounded by rownum on both ends .


select * from (select PART_NR,CTRY_CD,CUST_TRF_CD,VAL_FROM_DT,CHG_DT,NAT_HS_CD_2 , ROW_NUMBER() OVER(ORDER BY  CHG_DT,PART_NR) AS ID,
 COUNT(1) OVER ( ORDER BY 1 RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) ROW_COUNT from
((select TRIM(A.PART_NR) as PART_NR, TRIM(A.CTRY_CD) as CTRY_CD, TRIM(A.CUST_TRF_CD) as CUST_TRF_CD ,TO_CHAR(A.VAL_FROM_DT ,'yyyymmddhh24miss') as VAL_FROM_DT, TO_CHAR(A.CHG_DT ,'YYYYMMDDhh24miss') as CHG_DT,(case when (A.NAT_HS_CD is null  and A.CUST_TRF_CD is not null)  then
(select TRIM(C.NAT_HS_CD) from (select * from  (select CUST_TRF_CD, CTRY_CD, NAT_HS_CD ,VAL_FROM_DT from CLA_NAT_HS_DETAIL where CTRY_CD =421
 and INVALID_CD=0) AA where  VAL_FROM_DT= (select max(VAL_FROM_DT) from (select CUST_TRF_CD, CTRY_CD, NAT_HS_CD ,VAL_FROM_DT from CLA_NAT_HS_DETAIL
 where CTRY_CD  =421   and INVALID_CD=0) TT  where AA.CUST_TRF_CD=TT.CUST_TRF_CD and AA.CTRY_CD=TT.CTRY_CD) ) C where  C.CUST_TRF_CD=A.CUST_TRF_CD and
 C.CTRY_CD=A.CTRY_CD )  else TRIM(A.NAT_HS_CD)  end) as NAT_HS_CD_2 from cla_cust_part_ctry A where
 A.ctry_cd =421  and  A.CHG_DT between TO_DATE( '20110713000000', 'yyyymmddhh24miss') and TO_DATE( '20110714000000', 'YYYYMMDDhh24miss') and
 TRIM(A.PART_NR) not like '% %' ))  where  NAT_HS_CD_2 is not null) where ID > 20 and ID < 46 order by ID asc