Если не используется CROSS JOIN, CROSS APPLY или OUTER APPLY, требуется условие ON.
Отсюда и ошибка.
Хотя вы все еще можете сделать что-то вроде ... LEFT JOIN othertable ON (1=1)
.
Но вы можете переписать этот запрос, используя 2 левых соединения.
select
temp.*,
coalesce(repay.sum_payment, paynew.sum_payment) as value_table
from TBDA temp
left join TBDA_REPAYMENT repay on (repay.isdn = temp.isdn and repay.tr_month = temp.tr_month and repay.tr_year = temp.tr_year)
left join TBDA_PAYNEW paynew on (paynew.isdn = temp.isdn and paynew.tr_month = temp.tr_month and paynew.tr_year = temp.tr_year);
Обратите внимание, что есть предположение, что таблицы TBDA_REPAYMENT & TBDA_PAYNEW имеют уникальность для 3 полей, используемых в объединении (isdn, tr_month, tr_year).
Или можно использовать синтаксис OUTER APPLY.
И если нет уникальности (isdn, tr_month, tr_year), то вы можете использовать это для СУММЫ итога одновременно.
select
temp.*, repay.sum_payment as repay_sum_payment, paynew.sum_payment as paynew_sum_payment,
coalesce(repay.sum_payment, paynew.sum_payment) as value_table
from TBDA temp
outer apply
(
select nullif(sum(rp.sum_payment),0) as sum_payment
from TBDA_REPAYMENT rp
where rp.isdn = temp.isdn
and rp.tr_month = temp.tr_month
and rp.tr_year = temp.tr_year
) as repay
outer apply
(
select nullif(sum(pn.sum_payment),0) as sum_payment
from TBDA_PAYNEW pn
where pn.isdn = temp.isdn
and pn.tr_month = temp.tr_month
and pn.tr_year = temp.tr_year
) as paynew;
Пример фрагмента:
declare @TBDA table (isdn int, tr_month int, tr_year int);
declare @TBDA_REPAYMENT table (isdn int, tr_month int, tr_year int, sum_payment int);
declare @TBDA_PAYNEW table (isdn int, tr_month int, tr_year int, sum_payment int);
insert into @TBDA (isdn, tr_month, tr_year) values (1,6,2018),(2,6,2018);
insert into @TBDA_REPAYMENT (isdn, tr_month, tr_year, sum_payment) values (1,6,2018, 100);
insert into @TBDA_PAYNEW (isdn, tr_month, tr_year, sum_payment) values (1,6,2018, 200),(2,6,2018,100),(2,6,2018,200);
--
-- Using left join
--
select
temp.*, repay.sum_payment, paynew.sum_payment,
coalesce(repay.sum_payment, paynew.sum_payment) as value_table
from @TBDA temp
left join @TBDA_REPAYMENT repay on (repay.isdn = temp.isdn and repay.tr_month = temp.tr_month and repay.tr_year = temp.tr_year)
left join @TBDA_PAYNEW paynew on (paynew.isdn = temp.isdn and paynew.tr_month = temp.tr_month and paynew.tr_year = temp.tr_year);
--
-- Using outer apply
--
select
temp.*, repay.sum_payment as repay_sum_payment, paynew.sum_payment as paynew_sum_payment,
coalesce(repay.sum_payment, paynew.sum_payment) as value_table
from @TBDA temp
outer apply
(
select nullif(sum(rp.sum_payment),0) as sum_payment
from @TBDA_REPAYMENT rp
where rp.isdn = temp.isdn
and rp.tr_month = temp.tr_month
and rp.tr_year = temp.tr_year
) as repay
outer apply
(
select nullif(sum(pn.sum_payment),0) as sum_payment
from @TBDA_PAYNEW pn
where pn.isdn = temp.isdn
and pn.tr_month = temp.tr_month
and pn.tr_year = temp.tr_year
) as paynew;