Tengo mis columanas ya consultadas y mostrando:
Pais,
Estado
cantidad,
Retirado
Efectivos
En la columna Costo
hago una subconsulta para saber la suma de cada Estado
, la sub consulta por sí sola ya funciona y la probé por separado, pero al momento de implementar me suma de un estado
y me las muestra en todos el mismo monto.
declare @anho int select @anho = 2017; select (select x.nom from BD.dbo.Ent x where x.IdEnt = ch.CodEnt) as Pais, (select x.Nombre from BD.dbo.Co x where x.IdCo = ch.CodCo ) as Estado, (select COUNT(*) as total from BD.dbo.Mat x where x.IdC = ch.Cod) as cantidad, (select COUNT(*) as total from BD.dbo.Mat x where x.IdC = ch.Cod and FechaRetiro is not null) as Retirados, (select COUNT(*) as total from BD.dbo.Mat x where x.IdC = ch.Cod and FechaRetiro is null) as Efectivos, Costo = isnull( ( (SELECT SUM(cc.valor) FROM Cuenta cc inner join BD.dbo.Co c on cc.IdCo = c.IdC inner join BD.dbo.Mat xm on xm.Cod = cc.IdA and xm.FechaRetiro is null and cc.Gestion = @anho and xm.Gestion = @anho where cc.IdS = 24) ),0) from Cuenta cc, BD.dbo.CargaH ch group by ch.Gestion, ch.CodC, ch.Cod