Oracle

如何根據查詢中的列創建 100 的間隔?

  • September 5, 2022

我有一個具有以下結構的表:

create table item_test
(item_id       varchar2(10),
item_row      number)

範例數據如下,請注意Item_Row列中的數字從 1 開始,並以 1 遞增為一個數字,沒有任何間隙。我需要做的是([1-100] , [101-200] , [201-300] ,......)為每個Item_Id.

  Item_Id       Item_Row    
------------   ----------- 
   A               1           
   A               2            
   A              ...
   A              ...
   A              236  /* Item_Row starts from 1 and continues to 236 */

   B               1
   B              ...
   B              ...
   B              173  /* Item_Row starts from 1 and continues to 173 */
   
   C               1
   C               2
   C              ...
   C              ...
   C              300  /* Item_Row starts from 1 and continues to 300 */ 

結果將如下所示:

 Item_Id       RowNum_From     RowNum_From
------------   -----------     ----------- 
    A              1               100
    A             101              200
    A             201              236

    B              1               100
    B             101              173
    
    C              1               100 
    C             101              200
    C             201              300 

這有什麼特定的功能嗎?

訣竅是使用該trunc功能。

這是使用純 SQL 的解決方案:

create table item_test
(item_id       varchar2(10),
item_row      number);

insert into item_test
select 'A', level from dual connect by level <= 236
union all
select 'B', level from dual connect by level <= 173
union all
select 'C', level from dual connect by level <= 300;
commit;

select item_id, min(item_row) as item_row_from, max(item_row) as item_row_to
 from item_test
group by item_id, trunc(item_row-1, -2)
order by item_id, trunc(item_row-1, -2);

結果:

ITEM_ID    ITEM_ROW_FROM ITEM_ROW_TO
---------- ------------- -----------
A                      1         100
A                    101         200
A                    201         236
B                      1         100
B                    101         173
C                      1         100
C                    101         200
C                    201         300

8 rows selected.

引用自:https://dba.stackexchange.com/questions/316432