Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group sequence numbers in oracle?

Tags:

oracle

I have a string which is years separated by comma.

For example 2000,2001,2002,2005,2006,2007 and 2010.

I want to group the consecutive numbers.

My output should be 2000-2003,2005-2007 and 2010. Is there any way to do this in Oracle Stored procedure?

like image 552
bhuvana Avatar asked Apr 11 '13 11:04

bhuvana


People also ask

How do I add a sequence number in Oracle query?

The syntax to create a sequence in Oracle is: CREATE SEQUENCE sequence_name MINVALUE value MAXVALUE value START WITH value INCREMENT BY value CACHE value; sequence_name. The name of the sequence that you wish to create.

Can we modify sequence in Oracle?

Use the ALTER SEQUENCE statement to change the increment, minimum and maximum values, cached numbers, and behavior of an existing sequence. This statement affects only future sequence numbers.

Can we use Rownum with group by in Oracle?

HAVING refers to properties of groups created by GROUP BY , not to individual rows. You can't use ROWNUM in HAVING any more than you can use BYTES , or any other expression that may have different values for rows within a single group.

How do you sequence numbers in SQL?

The syntax to create a sequence in SQL Server (Transact-SQL) is: CREATE SEQUENCE [schema.] sequence_name [ AS datatype ] [ START WITH value ] [ INCREMENT BY value ] [ MINVALUE value | NO MINVALUE ] [ MAXVALUE value | NO MAXVALUE ] [ CYCLE | NO CYCLE ] [ CACHE value | NO CACHE ]; AS datatype.


1 Answers

Disclaimer - I don't recommend using this solution "as is", but it can give ideas, and it was fun writing it

I assume you have a column with the csv strings in a table.

If you're using oracle 11gR2 then you can use recursive CTEs-
Here is a sqlfiddle demo

with t as 
(
  select replace(replace(v, ' and ', ','), ' ','') v
  from strings
  ),
rcte(text, token, res) as
(
  select v, regexp_substr(v, '^\d*[^,]'), regexp_substr(v, '^\d*[^,]') ||'-'
  from t
  union all
  select regexp_replace(text, '^\d*,', ''), 
         regexp_substr(text, '^\d*[^,]'),
         case when regexp_substr(text, '^\d*[^,]') = token then
                   res
              when regexp_substr(text, '^\d*[^,]') = token+1 then  
                   regexp_replace(res, '-\d*$', '-'||(token+1))
              else rtrim(res, '-') || ',' || regexp_substr(text, '^\d*[^,]') || '-' 
         end
  from rcte
  where text <> token
  )
select rtrim(res, '-') from rcte
where text = regexp_substr(rtrim(res, '-'), '\d*$');

(This can be done without regular expressions as well)

like image 75
A.B.Cade Avatar answered Oct 11 '22 15:10

A.B.Cade