Question

I have data in table as below :

Three Columns

 date1 fromdate value
 ---------------------
 14     0       150
 14     2       150
 14     3       150
 14     4       120
 14     5       120
 14     6       150
 14     7       150 

I need to write sql query to get data in below format:

 Date1 fromdate todate value
 ----------------------------
 14     0       3      150
 14     4       5      120
 14     6       7      150

Is this possible to do with SQL query in oracle ?

Was it helpful?

Solution

You need to split your rows with the value 150 into two separate sections. You can do this by using analytic functions. The lead function allows you to look at the value of the next row by some order. In this case you want to find when you have a different value order by your fromdate:

select lead(value) over (order by fromdate) from tab;

You can then compare this to the current value to see when they change, outputting a discriminator when they do:

select value, case when ld <> value or ld is null then rownum end c from (
  select value, lead(value) over (order by fromdate) ld from tab
)

VALUE, C
-----------
150    null
150    null
150    3
120    null
120    5
150    null
150    7

You then need to "fill out" the discriminator to replace the nulls. This can be done with analytics again, selecting the min discriminator value by fromdate descending. You can then group by this value to give you the output you want:

select date1, value, d, min(fromdate), max(fromdate)
from (
  select date1, fromdate, value,
         --"fill down" the discriminator, so you can group by it at the next level 
         min(c) over (order by fromdate desc) d 
  from (
    select date1, fromdate, value, ld, 
           --compare the next value with the current, if they're different
           --show an indicator
           case when value <> ld or ld is null then rownum else null end c
    from (
      select date1, fromdate, value,lead(value) over (order by fromdate) ld
      from tab
    )
  )
)
group by date1, value, d

OTHER TIPS

Please try:

SELECT
  Date1, 
  MIN(fromdate) FromDate, 
  MAX(fromdate) ToDate, 
  "Value"
FROM
  "YourTable" 
GROUP BY Date1, "Value";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top