I don't understand the declare
blocks. They are unnecessary and I think the above query has some issues.
Since you need 6 columns only, please check this query. I am not sure this is what you need.
SELECT
a.dist_code_combination_id var1,
a.def_acctg_accrual_ccid var2,
a.invoice_id,
b.column4,
(SELECT segment FROM gl_code_combinations WHERE code_combination_id = a.dist_code_combination_id) AS segment1,
(SELECT segment FROM gl_code_combinations WHERE code_combination_id = a.def_acctg_accrual_ccid) AS segment2
FROM
AP_invoice_distributions_all a
JOIN
table2 b
ON
a.invoice_id = b.column4;
I just thought you want to rename a.dist_code_combination_id
to var1
...