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
CREATE TABLE #voucherDr
-- And sample data in consumable form
INSERT INTO #voucherCr
UNION ALL SELECT 2,'PAYMENT','R',1,1,55000
INSERT INTO #voucherDr
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
WHERE crparty = 2
SELECT vouchertype, voucherprefix, voucherno, drparty, NULL, dramount
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.
My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!
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?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables
, an Easter SQL
, Time Slots
and Self-maintaining, Contiguous Effective Dates in Temporal Tables