Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

347
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda