Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 Database Design and Application Architecture
 Create union qry

Author  Topic 

ranjeet_dutt
Starting Member

4 Posts

Posted - 2014-04-21 : 05:26:45
hi all, i am newbie in sql
i am using sqlceserver in my vb.net application
i want to create a query likewise:

VoucherNo VoucherDate CreditAmount DebitAmount Balance Cr/Dr
---------------------------------------------------------------------------
RC001 01/01/2014 10000.00 0.00 10000.00 Cr
IN001 01/01/2014 0.00 12000.00 2000.00 Dr
---------------------------------------------------------------------------

Receipt Table
-------------
ReceiptNo: RC001
ReceiptDate: 01/01/2014
Amount: 10000.00

Invoice Table
-------------
InvoiceNo: IN001
InvoiceDate: 01/01/2014
Amount: 12000.00

please advise code
Ranjeet

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2014-04-21 : 06:40:15
Haven't tested this but should be close.

;with cte1 as
(
select VoucherNo = ReceiptNo ,
VoucherDate = ReceiptDate ,
CreditAmount = 0.00 ,
DebitAmount = Amount
from Receipt
union all
select VoucherNo = InvoiceNo ,
VoucherDate = InvoiceDate ,
CreditAmount = Amount ,
DebitAmount = 0.00
from Invoice
),
cte2 as
(select *, seq = row_number() over (order by VoucherDate) from cte1)
cte3 as
(
select VoucherNo, VoucherDate, CreditAmount, DebitAmount,
Balance = CreditAmount - DebitAmount, seq = 1
from cte2 where seq = 1
union all
select cte2.VoucherNo, cte2.VoucherDate, cte2.CreditAmount, cte2.DebitAmount,
Balance = cte3.Balance + cte2.CreditAmount - cte2.DebitAmount, seq = cte3.seq + 1
from cte3,cte2 where cte3.seq + 1 = cte2.seq
)
select VoucherNo, VoucherDate, CreditAmount, DebitAmount,
Balance = case when Balance < 0 then Balance * -1 else Balance end ,
case when Balance < 0 then 'DR' else 'CR' end
from cte3
order by seq

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

ranjeet_dutt
Starting Member

4 Posts

Posted - 2014-04-21 : 14:11:58
sir thanks for your reply but i am using sqlce, hence this code might not working coming error
Go to Top of Page

ranjeet_dutt
Starting Member

4 Posts

Posted - 2014-04-21 : 17:29:56
worked with sql server thanks again
Go to Top of Page

ranjeet_dutt
Starting Member

4 Posts

Posted - 2014-04-21 : 17:30:25
one more thing

can i add opening balance in this query?
Go to Top of Page
   

- Advertisement -