简体   繁体   中英

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

SELECT SUM(grades)
FROM
(
SELECT grade as grades
FROM "GradesTable"
 WHERE status='success' AND student_ID=1
 ORDER BY grade DESC
 LIMIT 50
) z

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM