Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's on way to do it.</p> <ol> <li>Select all records from <code>my_table</code> where the balance is positive.</li> <li>Do a self-join and get all the records that have a <code>as_on_date</code> is greater than the current row, but the <code>amounts</code> are in negative</li> <li>Once we get these, we cut-off the rows <code>WHERE</code> the <code>date difference</code> between the current and the previous <code>row</code> for <code>as_on_date</code> is <code>&gt; 1</code>. We then filter the results a <code>outer sub query</code></li> <li>The Final <code>select</code> just groups the rows and gets the <code>min, max</code> values for the filtered rows which are grouped.</li> </ol> <p>Query:</p> <pre><code>SELECT account_no, min(case when row_number = 1 then balance end) as balance, max(mt2_date) as As_on_date, max(mt2_date) - mt1_date as Days_passed, min(mt2_date) as Start_date FROM ( SELECT *, MIN(break_date) OVER( PARTITION BY mt1_date ) AS min_break_date, ROW_NUMBER() OVER( PARTITION BY mt1_date ORDER BY mt2_date desc ) AS row_number FROM ( SELECT mt1.account_no, mt2.balance, mt1.as_on_date as mt1_date, mt2.as_on_date as mt2_date, case when mt2.as_on_date - lag(mt2.as_on_date,1) over () &gt; 1 then mt2.as_on_date end as break_date FROM my_table mt1 JOIN my_table mt2 ON ( mt2.balance &lt; mt1.balance AND mt2.as_on_date &gt; mt1.as_on_date ) WHERE MT1.balance &gt; 0 order by mt1.as_on_date, mt2.as_on_date ) sub_query ) T WHERE min_break_date is null OR mt2_date &lt; min_break_date GROUP BY mt1_date, account_no </code></pre> <p><a href="http://sqlfiddle.com/#!12/93c56" rel="nofollow"><strong>SQLFIDDLE</strong></a></p> <p>I have a added a few more rows in the FIDDLE, just to test it out</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload