Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
group results in one single line with similar ids

I have the following SQL query:

SELECT 
cat,
CASE WHEN CCR.id_invoice_type = 52 THEN CCR.amount END earn,
CASE WHEN CCR.id_invoice_type = 54 THEN CCR.amount END expend,

FROM fac_invoices CCR
GROUP BY CCR.cat, CCR.id_invoice_type , CCR.amount
ORDER BY CCR.cat

with the following result:

cat earn    expend
=======================
3   50,4    (null)
3   (null)  (null)
3   (null)  35
5   160,7   (null)
5   (null)  (null)
5   (null)  35
10  50,4    (null)
10  (null)  (null)
10  (null)  35

But I wanna get the current result

cat earn    expend
=======================
3   50,4    35
5   160,7   35
10  50,4    35

As you can see I have tried to group the fields but it's not working. What's wrong in my query? Or which other functions should I use to get the desired result?

Thanks in advance.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You need to simplify the GROUP BY. You want only one row per cat, so that should be the only key in the GROUP BY. One way to do what you want is string_agg():

SELECT cat,
       STRING_AGG(CASE WHEN CCR.id_invoice_type = 52 THEN CCR.amount END) as earn,
       STRING_AGG(CASE WHEN CCR.id_invoice_type = 54 THEN CCR.amount END) as expend
FROM fac_invoices CCR
GROUP BY CCR.cat
ORDER BY CCR.cat;

Or MAX() also works in your case.

SELECT cat,
       MAX(CASE WHEN CCR.id_invoice_type = 52 THEN CCR.amount END) as earn,
       MAX(CASE WHEN CCR.id_invoice_type = 54 THEN CCR.amount END) as expend
FROM fac_invoices CCR
GROUP BY CCR.cat
ORDER BY CCR.cat;
over 4 years ago · Santiago Trujillo Relatório

0

You should use string_agg() then like

CASE WHEN CCR.id_invoice_type = 52 THEN string_agg(CCR.amount,',') END earn,
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda