Buen día/tarde/noche, según aplique, compañeros del Foro.
Tengo ésta sentencia en MS SQL Server (la versión más reciente, 2018):
Código SQL
[-]select cac.mcuenta,
cac.mnombre,
ISNULL(inicial.saldo, 0) as inicial,
ISNULL(enero.haber, 0) as enerohaber,
ISNULL(enero.debe, 0) as enerodebe,
ISNULL(enero.saldo, 0) as enerosaldo,
ISNULL(febrero.haber, 0) as febrerohaber,
ISNULL(febrero.debe, 0) as febrerodebe,
ISNULL(febrero.saldo, 0) as febrerosaldo,
ISNULL(marzo.haber, 0) as marzohaber,
ISNULL(marzo.debe, 0) as marzodebe,
ISNULL(marzo.saldo, 0) as marzosaldo,
.
.
.
.
.
ISNULL(diciembre.haber, 0) as diciembrehaber,
ISNULL(diciembre.debe, 0) as diciembredebe,
ISNULL(diciembre.saldo, 0) as diciembresaldo
from cacuent as cac
left join (
select tr.tcuenta, sum(tdebe) as debe, sum(thaber) as haber, sum(tdebe)-sum(thaber) as saldo
from cdtrans as tr
where left(tperiod, 4) < 2018
and tcuenta is not null
group by tcuenta) as inicial on cac.MCUENTA = inicial.TCUENTA
left join (
select tr.tcuenta, sum(tdebe) as debe, sum(thaber) as haber, sum(tdebe)-sum(thaber) as saldo
from cdtrans as tr
where left(tperiod, 4) = 2018
and right(tperiod, 2) = 1
and tcuenta is not null
group by tcuenta) as enero on cac.MCUENTA = enero.TCUENTA
left join (
select tr.tcuenta, sum(tdebe) as debe, sum(thaber) as haber, sum(tdebe)-sum(thaber) as saldo
from cdtrans as tr
where left(tperiod, 4) = 2018
and right(tperiod, 2) = 2
and tcuenta is not null
group by tcuenta) as febrero on cac.MCUENTA = febrero.TCUENTA
left join (
select tr.tcuenta, sum(tdebe) as debe, sum(thaber) as haber, sum(tdebe)-sum(thaber) as saldo
from cdtrans as tr
where left(tperiod, 4) = 2018
and right(tperiod, 2) = 3
and tcuenta is not null
group by tcuenta) as marzo on cac.MCUENTA = marzo.TCUENTA
.
.
.
left join (
select tr.tcuenta, sum(tdebe) as debe, sum(thaber) as haber, sum(tdebe)-sum(thaber) as saldo
from cdtrans as tr
where left(tperiod, 4) = 2018
and right(tperiod, 2) = 12
and tcuenta is not null
group by tcuenta) as diciembre on cac.MCUENTA = diciembre.TCUENTA
La cual es ineficiente, ya que puede o no tener datos para ciertos meses. El problema no es ése, sino que se darán cuenta que es básicamente el año en curso (
where left(tperiod, 4) = 2018) e ir cambiando el mes (
and right(tperiod, 2) = 'n'). La duda o pregunta es: ¿podrían orientarme respecto al mejoramiento de la sentencia (no soy muy ducho en SQL Server) o qué faltaría para que el rendimiento se incremente?
De antemano, muchas gracias.