Normally, most people won't answer your question because you didn't take the time to provide DDL and sample data in consumable form. There are many good links to how to do this, but since it is Christmas and I'm feeling charitable I will demonstrate and explain with comments in the code.
-- Next time - provide DDL
CREATE TABLE #voucherCr
(srno INT
,vouchertype VARCHAR(20)
,voucherprefix CHAR(1)
,voucherno INT
,crparty INT
,cramount MONEY)
CREATE TABLE #voucherDr
(srno INT
,vouchertype VARCHAR(20)
,voucherprefix CHAR(1)
,voucherno INT
,drparty INT
,dramount MONEY)
-- And sample data in consumable form
INSERT INTO #voucherCr
SELECT 1,'PURCHASE','P',1,2,55000
UNION ALL SELECT 2,'PAYMENT','R',1,1,55000
INSERT INTO #voucherDr
SELECT 1,'PURCHASE','P',1,4,54000
UNION ALL SELECT 2,'PURCHASE','P',1,5,1000
UNION ALL SELECT 3,'PAYMENT','R',1,2,55000
SELECT VTYPE=vouchertype, VPRE=voucherprefix, VNO=voucherno
,AGAINSTPARTY=crparty
,CREDIT=cramount, DEBIT=NULL
FROM #voucherCr
WHERE crparty = 2
UNION ALL
SELECT vouchertype, voucherprefix, voucherno, drparty, NULL, dramount
FROM #voucherDr
WHERE drparty = 2
-- Always use temporary tables and don't forget to drop them
DROP TABLE #voucherCr
DROP TABLE #voucherDr
This query is only meant to get you started. It does not produce the expected results in the AGAINSTPARTY column, because frankly I couldn't see a pattern for how you came up with 1 and 4.
Play around with it and see if you can figure out how to make it work to get exactly the results you were expecting.
Merry Christmas.
My thought question: Have you ever been told that your query runs too fast?
My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.
Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
Since random numbers are too important to be left to chance, let's generate some![/url]
Learn to understand recursive CTEs by example.[/url]
[url url=http://www.sqlservercentral.com/articles/St