【问题标题】:PostgreSQL: How to multiply two columns and display result in same query?PostgreSQL:如何将两列相乘并在同一查询中显示结果?
【发布时间】:2015-06-18 07:25:58
【问题描述】:

我有一个查询,它的 select 语句是这样的:

select Greatest(p.price,0) as newprice, sum(q.qty) as qty
from ....

它给了我:

     newprice qty
      10      1
      0       1
      100     2
      1       2

我想将 newprice 与 qty 相乘得到:

    newprice  qty   result
      10      1      10
      0       1      0
      100     2     200
      1       2      2

当我尝试做 select Greatest(p.price,0) as newprice, sum(q.qty) as qty, newprice * qty 它说

ERROR: column "newprice" does not exist

我真的不需要这个额外的专栏。

我真正想要的是:SUM(Greatest(p.price,0) * SUM(q.qty)) 应该给出值 212 但它说 ERROR: aggregate function calls cannot be nested

基本上我只需要将两列相乘并将结果相加。 我知道我可以使用类似于here 所示的 CTE,但我想知道是否有更简单的方法,代码更少。

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    你可以重复你写的:

    select Greatest(p.price,0) as newprice,
           sum(q.qty) as qty,
           Greatest(p.price,0) * sum(q.qty) as result
    from ...
    

    或者,您可以将您的 select 语句 包装到 临时派生表 (PostgreSQL: using a calculated column in the same query)

    select tmp.newprice,
           tmp.qty,
           tmp.newprice * tmp.qty as result
    from (
        select Greatest(p.price,0) as newprice,
               sum(q.qty) as qty
        from ...
    ) as tmp
    

    【讨论】:

      【解决方案2】:

      查询应该是这样的:

      select *, newprice*qty from
      (
          select Greatest(p.price,0) as newprice, sum(q.qty) as qty
          from ....
      ) T
      

      select Greatest(p.price,0) as newprice, sum(q.qty) as qty, Greatest(p.price,0)*sum(q.qty) as result
      from ....
      

      更新:

      您在查询中使用group by(我推测是因为聚合)并且为了找到 sum(newprice*qty),您需要一个子选择:

      select sum(newprice*qty) from
      (
          select Greatest(p.price,0) as newprice, sum(q.qty) as qty
          from ....
      ) T
      

      【讨论】:

      • 我试图避免这种情况......因为我将不得不用另一个选择包装它以获得最终值(在我的示例中为 212)
      【解决方案3】:

      试试这个:

      select sum(price*qty) as result
      from yourtable;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-27
        • 2012-06-27
        • 1970-01-01
        • 1970-01-01
        • 2011-03-17
        相关资源
        最近更新 更多