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

349
Visualizações
Calculate the sum of a query that uses order by and limit Postgres

The following query returns a table of grades. I want the sum of it and i cant figure out how to do it.

SELECT grade
 FROM "GradesTable"
 WHERE status='success' AND student_ID=1
 ORDER BY grade DESC
 LIMIT 50

I get this error:

ERROR: column "grade" must appear in the GROUP BY clause or be used in an aggregate function

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

0

SELECT SUM(grades)
FROM
(
SELECT grade as grades
FROM "GradesTable"
 WHERE status='success' AND student_ID=1
 ORDER BY grade DESC
 LIMIT 50
) z
over 4 years ago · Santiago Trujillo Relatório

0

The problem here is the ORDER BY clause which you would know if you pasted the full error, instead of forcing us to recreate your problem from scratch because you didn't provide the DDL and data.

CREATE TABLE "GradesTable" ( status text, student_id int, grade int );
INSERT INTO "GradesTable" (status, student_id, grade) VALUES
  ('success', 1, 80),
  ('success', 1, 100);

Query

SELECT sum(grade)                                                    FROM "GradesTable"
 WHERE status='success' AND student_ID=1
 ORDER BY grade DESC
 LIMIT 50
;
ERROR:  column "GradesTable.grade" must appear in the GROUP BY clause or be used in an aggregate function
LINE 4:  ORDER BY grade DESC

However this works,

SELECT sum(grade)
 FROM "GradesTable"
 WHERE status='success' AND student_ID=1
 LIMIT 50
;
 sum 
-----
 180
(1 row)

But you shouldn't have a LIMIT if you have only one agg that can only ever return one row.

SELECT sum(grade)
 FROM "GradesTable"
 WHERE status='success' AND student_ID=1
;

If you meant to order by sum(grade) you can do that, but you lose the ability to order by grade the second you aggregate it together. However, in this example it doesn't matter because you're only returning one row.

And as a separate note you should never quote identifiers in PostgreSQL. Make everything lowercase, never quote table names or column names.

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