Click here to Skip to main content
15,913,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello friends.
I have the following table:

ID SERIAL STATUS
1 10001 1
2 10002 1
3 10003 1
4 10004 0
5 10005 0
6 10006 1
7 10007 1
8 10008 0
9 10009 1
10 10010 1

I need a query where i will have the serial range with status 1. Like as per the above table data..I need the out put to be 10001 to 10003,10006 to 10007,10009 to 10010.
How can I do that in using SQL.
Any help would be highly appreciated.
Posted

Have a look at the new ROLLUP option in SQL Server 2008.
It should allow you to group data by range.

Here[^] is a good example.
 
Share this answer
 
Comments
Pallab_GT 2-Feb-12 2:31am    
It Has to be done in oracle...is there a way in oracle?
Jörgen Andersson 9-Feb-12 15:57pm    
Rollup works in Oracle, but I don't see how you can use it for this purpose
It could probably be optimized, but this query will do the trick, if you have Oracle version 10g or later:
SQL
WITH prv_nxt AS (
    SELECT  serial
           ,Lag(status,1,0) OVER (ORDER BY serial) previous
           ,status
           ,Lead(status,1,0) OVER (ORDER BY serial) nxt
    FROM    temp
    )
,CHANGE AS ( 
    SELECT  serial
           ,1 CHANGE
    FROM    prv_nxt
    WHERE   previous = 0
    AND     status = 1
    UNION
    SELECT  serial
           ,0 CHANGE
    FROM    prv_nxt
    WHERE   status = 1
    AND     nxt = 0
    )
, start_stop AS (
    SELECT  serial startserial
           ,Lead(serial,1,NULL) OVER (ORDER BY serial) stopserial
           ,change
    FROM    CHANGE
    )
SELECT  startserial || ' to ' || stopserial range
FROM    start_stop
WHERE   CHANGE = 1
 
Share this answer
 
Select ID, SERIAL, STATUS from [Table]
Where [STATUS] = 1

--or


Select ID, SERIAL, STATUS from [Table]
Where [STATUS] = '1'




--OutPut


ID SERIAL STATUS
1 10001 1
2 10002 1
3 10003 1
6 10006 1
7 10007 1
9 10009 1
10 10010 1



[Table] -- name of your table

[STATUS] = '1' --if the [STATUS] is String or Varchar type
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900