5
I’m having a problem with a basic consultation of SQL, is for a migration of database.
The query aims to bring data from the table of ASSOCIADOS/CLIENTES
, but beyond this table I have another MENSALIDADES
, and two of the fields I need in this extraction is the expiration of the last monthly payment and its value.
I’m using the MAX
to bring the monthly fee and so far so good, when I put:
CONVERT (VARCHAR,MAX(MEN.VENCIMENTO),102) as data_inicio_ciclo
the value returned is actually the last monthly payment and does not duplicate the information, the value in the query it brings all the data, and need only the value of the last:
MEN.Valor AS valor_total_venda
Below the query in SQL and the return (PRINT) with the VALUE and WITHOUT THE VALUE
SELECT
ASS.Inscricao as numero_contrato,
CONVERT (VARCHAR, ASS.data, 102) as data_contrato,
ASS.grupo as id_tipo_contrato,
ASS.TipoVenda as id_tipo_venda,
ASS.Inscricao as codigo_cliente_antigo,
CONVERT (VARCHAR,ASS.data, 102) as data_vigencia_inicial,
CONVERT (VARCHAR,ASS.DataContratoVigenciaFinal, 102) as data_vigencia_final,
CONVERT (VARCHAR,ASS.DiaVenc, 102) as dia_vencimento,
ASS.AssTipoCobranca as id_preferencia_faturamento,
ASS.AssTipoCobranca as id_periodicidade,
ASS.AssTipoCobranca as ciclo_atual,
CONVERT (VARCHAR,MAX(MEN.VENCIMENTO),102) as data_inicio_ciclo,
ASS.status as registro_ativo,
CONVERT (VARCHAR,ASS.DataStatus, 102) as data_cancelamento,
ASS.MotivoStat as id_motivo_cancelamento,
ASS.Obs1 as observacoes1, -- REVALIDAR
ASS.Obs2 as observacoes1, -- REVALIDAR
MEN.Valor as valor_total_venda
from Associados as ASS
inner join mensalidade as MEN ON MEN.INSCRICAO=ASS.INSCRICAO
where ASS.Inscricao ='1'
GROUP BY
ASS.Inscricao,
ASS.Data,
ASS.Grupo,
ASS.TipoVenda,
ASS.DataContratoVigenciaFinal,
ASS.DiaVenc,
ASS.AssTipoCobranca,
ASS.Status,
ASS.DataStatus,
ASS.MotivoStat,
ASS.Obs1,
ASS.Obs2,
men.valor
it seems (by description, should put more data to facilitate the analysis) that some of the fields grouped is with equal values so is doubling, try to sort to take the doubt
– Ricardo Pontual
The column
MEN.Valor
returns the total of all grouped records?– RXSD
It is not bringing equal records, brings several salaries and in some cases appears the men.value grouped.
– José Ronaldo dos Santos Jr