Tenho uma tabela (OcorrMes) que contém dois registros com o mesmo código de evento (codevento). Como os códigos de eventos são os mesmos, preciso que esse valores sejam somados uma única linha de retorno de consulta. Para tanto, desenvolvi a consulta abaixo, porém, o sistema está dando o erro abaixo. Sei que se eu incluir todos os campos no order by resolve o problema do erro. Mas, se eu fizer isso, daí o sistema não retorna o valor somado da forma que preciso. Como resolver?
Msg 8120, Level 16, State 1, Line 7
Column 'OcorrMes.REFERENCIA' is invalid in the select list because it is not contained in either an aggregate function
select
Right( '00000000' + Ltrim(Str( b.CodAgent )) + Ltrim(str(b.CodEmpre)), 8 ) CHAPA,
'31102014' DATA,
REPLICATE('0', 4 - LEN(a.codevento)) + RTrim(a.codevento) EVENTO,
'000:00' HORA,
isnull(a.REFERENCIA, 0) REF,
isnull(a.valor, 0) VALOR,
CAST(isnull(a.valor, 0) AS CHAR)+'N' VALORN,
'0' ZERO
from OcorrMes a, FUNCI b
where b.CODAGENT = a.CODAGENT
and b.CODEMPRE = a.CODEMPRE
and b.NUMREGISTRO is not null
and nrtppagto not in ('1', '2', '3', '5', '7', '8', '10', '11')
and b.codempre in (1)
and ano = 2014
and mês = 10
and codevento in ('4', '9', '10', '48', '50', '76', '137', '144', '10', '105', '149', '173', '935', '1076')
and Right( '00000000' + Ltrim(Str( b.CodAgent )) + Ltrim(str(b.CodEmpre)), 8 ) = '00589641'
and codevento = '0009'
group by b.codempre, b.codagent, a.codevento