0

I have table which has columns for credit and debit account as rows of periods '1-12' and also a opening balance which should carry into each period.

Table

Account  |Period   |Credit |Debits    |Opening Balance
1000       1          100     0           50          
1000       2           0      100         50          
.          .           .      .            .          
.          .           .      .            .          
1001       1          50      0           100         
1002       1          40      0           100         

But my problem here is can I duplicate or create 12 row with opening balance in each row for account 1001 and 1002??

2
  • you want to insert a blank row? I'm not sure I understand the question Commented Feb 26, 2013 at 3:21
  • In the above table i want to dynamically create a row say for Account ID 1001 (1001 2 0 0 100 and 1001 3 0 0 100 and so on)..thanks Commented Feb 26, 2013 at 3:27

1 Answer 1

1

Here is one method. It uses a join to a list of numbers to get all the combinations of periods and accounts. It then uses a correlated subquery to choose the most recent value for the balance.

This version uses MySQL syntax. The correlated subquery might use select top 1 or where rownum = 1 or something else depending on the database:

select t.account, n.n, coalesce(t.credit, 0) as credit,
       coalesce(t.debit, 0) as debit,
       (select balance
        from t t2
        where t2.account = t.account and
              t2.period <= t.period
        order by period desc
        limit 1
       ) as balance
from (select 1 as n union all select 2 union all select 3 union all select 4 union all
      select 5 union all select 6 union all select 7 union all select 8 union all
      select 9 union all select 10 union all select 11 union all select 12
     ) n left outer join
     t
     on t.period = n.n
Sign up to request clarification or add additional context in comments.

2 Comments

Still I can get only one row even though left Outer join should return all the 12 rows?? Am I doing anything wrong??
Think the problem here is it creates 12 rows but assigns 'NULL' in account column,but I want the account also to be duplicated..regards

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.