【问题标题】:Calculate the sum of a query that uses order by and limit Postgres计算使用 order by 和 limit Postgres 的查询的总和
【发布时间】:2017-09-18 16:19:13
【问题描述】:

以下查询返回成绩表。 我想要它的总和,我不知道该怎么做。

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

我收到此错误:

错误:列“等级”必须出现在 GROUP BY 子句中或被使用 在聚合函数中

【问题讨论】:

  • 我得到的错误来自这个查询:SELECT SUM(grade) FROM "GradesTable" WHERE status='success' AND student_ID=1 ORDER BY Grade DESC LIMIT 50
  • 您显示的查询不会产生该错误。请edit您的问题并添加真正的查询。不要在 cmets 中发布代码或附加信息
  • @a_horse_with_no_name 这不是真的,请参阅ORDER BY。这是我第一次认为你在与 PostgreSQL 无关的事情上错了。
  • @EvanCarroll:见这里:dbfiddle.uk/…
  • @a_horse_with_no_name 啊,我明白了。我刚刚读到的意思是当我做这个总和时(等级)

标签: sql postgresql aggregate-functions


【解决方案1】:

这里的问题是ORDER BY 子句,如果您粘贴了完整的错误,您就会知道它,而不是因为您没有提供 DDL 和数据而迫使我们从头开始重新创建您的问题。

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

查询

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

不管怎样,

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

但是,如果您只有一个只能返回一行的 agg,您就不应该有 LIMIT

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

如果您打算通过sum(grade) 订购,您可以这样做,但是您在将它们聚合在一起的第二秒就失去了通过grade 订购的能力。但是,在此示例中,这无关紧要,因为您只返回一行。

另外,你不应该在 PostgreSQL 中引用标识符。将所有内容设为小写,切勿引用表名或列名。

【讨论】:

    【解决方案2】:
    SELECT SUM(grades)
    FROM
    (
    SELECT grade as grades
    FROM "GradesTable"
     WHERE status='success' AND student_ID=1
     ORDER BY grade DESC
     LIMIT 50
    ) z
    

    【讨论】:

    • 请考虑添加解释,说明为什么这是正确答案。仅代码的答案并不倾向于教育读者。
    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    相关资源
    最近更新 更多