Teradata查询分页-每1000条记录批处理

时间:2018-12-17 20:43:34

标签: sql database teradata teradata-sql-assistant

我有这个Teradata查询:

WITH ID(ROW_NUM) AS 
(
    SELECT ROW_NUMBER() OVER (ORDER BY PRSN_ID) AS ROW_NUM
    FROM MyTable 
    WHERE ACTIVE_IND = 'Y' 
    GROUP BY PRSN_ID
)
SELECT ROW_NUM-ROW_NUM MOD 2 AS FirstIndex,
ROW_NUM-(ROW_NUM-1) MOD 2 AS SecondIndex
FROM ID
WHERE ROW_NUM MOD 2=1

此查询将生成一个ID列,结果将是这样:

FirstIndex    SecondIndex
0             1
2             3
4             5  
.             .
.             .
etc           etc

我想通过以下1000条记录将选择更改为批处理:

FirstIndex    SecondIndex
0             1000
1001          2000
2001          3000  
3001          4000
.             .
.             .
etc           etc

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您的计算很复杂:

   ROW_NUM-1 AS FirstIndex,
   ROW_NUM   AS SecondIndex

要获得所需范围,您只需修改计算,例如

SELECT 
   CASE WHEN ROW_NUM = 1 THEN 0 ELSE SecondIndex-999 END AS FirstIndex,
   (ROW_NUM+2)/2 * 1000 AS SecondIndex
FROM ID
WHERE ROW_NUM MOD 2=1

但是要对结果进行批处理什么

编辑:

尚不清楚为什么需要第二张表来计算范围,但这会为 n 行的任何页面大小创建从1开始的范围:

WITH ID(ROW_NUM) AS 
(  -- just to get some rows
    SELECT day_of_calendar AS row_num
    FROM sys_calendar.CALENDAR
    WHERE row_num BETWEEN 1 AND 10
)
SELECT 1000 AS RowsPerPage,
   Row_Num AS page_num,
   rownum_to - (RowsPerPage-1) AS rownum_from,
   page_num * RowsPerPage AS rownum_to
FROM ID
GROUP BY page_num
ORDER BY page_num

RowsPerPage     page_num     rownum_from     rownum_to
       1000            1               1          1000
       1000            2            1001          2000
       1000            3            2001          3000
       1000            4            3001          4000
       1000            5            4001          5000
       1000            6            5001          6000
       1000            7            6001          7000
       1000            8            7001          8000
       1000            9            8001          9000
       1000           10            9001         10000

答案 1 :(得分:0)

嗨,您可以尝试以下查询一次,这将为您提供所需的顺序。

select ROW_NUM,FirstIndex, coalesce(case when SecondIndex<1000 then (SecondIndex+2000) else (SecondIndex+1000) end,FirstIndex+1001) as SecondIndex from 
(SELECT ROW_NUM,
case when (FirstIndex < 1000) then (FirstIndex+1001) else (FirstIndex+1) end as FirstIndex,
(min(FirstIndex) OVER(ORDER BY FirstIndex ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING))  SecondIndex
FROM (Select (ROW_NUMBER() OVER (ORDER BY PRSN_ID)-1) AS ROW_NUM,(ROW_NUMBER() OVER (ORDER BY PRSN_ID)-1) AS FirstIndex from Mytable GROUP BY PRSN_ID) A) B
order by ROW_NUM;