问题
I have a large table 1 million+ rows with a numeric column as primary key. I was trying for an Oracle sql query to get a split of size say 500. So that I have sort of buckets that have 500 records each and give their max and min value in that bucket. sample data
pk_column column1 column2 column3
1002 abcd 1234 15-apr-20
1004 efgh 3435 14-apr-20
1007 ijkl 8855 16-apr-20
....
....
....
2002 asdf 8565 17-apr-20
2005 efgh 5894 14-apr-20
the desired output is something like below
bucket_no no_of_element min_value max_value
1 500 1002 2002
2 500 2005 3002
3 500 3003 4002
4 480 4003 4500
The code that I could come up with using NTILE or WIDTH_BUCKET is not able to decide the number of bucket size so that no of element is kind of fixed. As the number of elements keep changing , I am unable to find a way to calculate the bucket count dynamically and use it in the NTILE or WIDTH_BUCKET window function. Use of LEAD and LAG function in a hierarchical way was a lot confusing. Could anyone suggest how to tackle this.
回答1:
You can use the analytical function ROW_NUMBER
as follows:
SELECT
RN AS BUCKET_NO,
COUNT(1) AS NO_OF_ELEMENT,
MIN(PK_COLUMN) AS MIN_VALUE,
MAX(PK_COLUMN) AS MAX_VALUE
FROM
( SELECT T.*,
MOD(ROW_NUMBER() OVER(ORDER BY PK_COLUMN) - 1, 500) + 1 RN
FROM YOUR_TABL T
)
GROUP BY RN
来源:https://stackoverflow.com/questions/61229208/how-to-split-a-table-rows-into-fixed-size-chunk-in-oracle