postgres 中计算值的列别名

发布于 2024-09-02 08:08:23 字数 222 浏览 4 评论 0原文

我尝试在 postgres 中使用别名来执行此查询,但 postgres 停止并抱怨错误:列“小计”不存在

SELECT SUM(price) AS subtotal, 
       subtotal * 3.0 AS fees,
       (subtotal + fees) AS total
  FROM cart

您不能使用别名作为下一列的一部分吗?

I tried to uses aliases in postgres for this query, but postgres stops and complains that ERROR: column "subtotal" does not exist

SELECT SUM(price) AS subtotal, 
       subtotal * 3.0 AS fees,
       (subtotal + fees) AS total
  FROM cart

You cannot use aliases as part of your next column?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沫离伤花 2024-09-09 08:08:23

不可以,您不能在同一 SQL 语句中重复使用列别名 - 使用:

SELECT SUM(t.price) AS subtotal,
       SUM(t.price) * 3.0 AS fees,
       SUM(t.price + fees) AS total
  FROM CART t

您可以在 ORDER BY 子句中引用列别名,某些数据库还支持在 GROUP BY中引用>HAVING 子句。

No, you can not re-use a column alias within the same SQL statement - use:

SELECT SUM(t.price) AS subtotal,
       SUM(t.price) * 3.0 AS fees,
       SUM(t.price + fees) AS total
  FROM CART t

You can reference the column alias in the ORDER BY clause, some databases also support referencing in the GROUP BY and HAVING clauses.

关于您的答案的问题:

    SELECT SUM(t.price) AS subtotal,
      SUM(t.price) * 3.0 AS fees,
      SUM(t.price + fees) AS total
    FROM CART t

如果您无法在同一 SQL 语句中重复使用列别名,那么不应该是以下情况:

   SELECT SUM(t.price) AS subtotal,
     SUM(t.price) * 3.0 AS fees,
     SUM(t.price + (t.price * 3.0)) AS total
   FROM CART t

Question about your answer:

    SELECT SUM(t.price) AS subtotal,
      SUM(t.price) * 3.0 AS fees,
      SUM(t.price + fees) AS total
    FROM CART t

Should it not be the following if you can not re-use a column alias within the same SQL statement:

   SELECT SUM(t.price) AS subtotal,
     SUM(t.price) * 3.0 AS fees,
     SUM(t.price + (t.price * 3.0)) AS total
   FROM CART t
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文