select t.ordprod as ordprod,t.prodno as prodno, t.estado as estado,t.dataini as dataini,
t.datafim as datafim,t.atrasado as atrasado,
t.stamp as stamp,SUM(((isnull(us.custoproducao_hora,0) * isnull(equip.horashomem,0))
+ (isnull(equip.horas,0) * isnull(prod.custohora,0)))) as custo
from(
select ficha.ordem_producao as ordprod,
ficha.producaono as prodno,
ficha.estado_producao as estado,
ficha.dataini_producao as dataini,
ficha.data_concluido as datafim,
ficha.ousrdata as ousrdata,
ficha.uXXXX_producaostamp as stamp,
case when
((data_previsao_conclusao <> '19000101' and
concluido=1 and
data_previsao_conclusao < data_concluido)
or (data_previsao_conclusao <> '19000101' and
concluido=0 and
data_previsao_conclusao < getdate()) ) then 1
else 0 end as atrasado
from uXXXX_producao as ficha)t
left join uXXXX_equipamento_utilizados as equip on equip.uXXXX_producaostamp=t.stamp
left join uXXXX_producaous as us on equip.usstamp=us.userstamp
left join uXXXX_equipamentos_producao as prod on
prod.uXXXX_equipamentos_producaostamp = equip.uXXXX_equipamentos_producaostamp
where (t.estado='#1#' or '#1#'='Todos') and t.ousrdata >= '#2#' and t.ousrdata <= '#3#'
group by t.ordprod,t.prodno, t.estado,t.dataini, t.datafim, t.stamp, t.atrasado
order by estado, prodno