sql - 将根据 CASE 语句计算的两列相乘

标签 sql postgresql group-by case case-when

我正在使用 CASE 语句在 PostgreSQL 中执行 SQL 查询,如下所示:

SELECT
    CASE column1
        WHEN something THEN 10
        ELSE 20
        END AS newcol1
    CASE column12
        WHEN something THEN 30
        ELSE 40
        END AS newcol2
COUNT(column3) newcol3
FROM table
GROUP BY newcol1,newcol2,newcol3

我需要第四列,它必须是 newcol2 * newcol3 的结果,我该怎么做?

如果我把 (newcol2 * newcol3) AS newcol4 我得到一个语法错误。

最佳答案

如果有帮助的话,您始终可以使用 CTE 将事物抽象到不同的级别 - 类似于 ...

With CTE as
(
 SELECT
  CASE column1
    WHEN something THEN 10
    ELSE 20
    END AS newcol1,
  CASE column12
    WHEN something THEN 30
    ELSE 40
    END AS newcol2,
  column3,
 FROM table
)
SELECT
  newcol1, newcol2,
  count(column3) as newcol3,
 (newcol2 * newcol3) AS newcol4
FROM CTE 
GROUP BY newcol1,newcol2,newcol3

关于sql - 将根据 CASE 语句计算的两列相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15437704/

相关文章:

sql - date_format 不是 sql 中可识别的内置函数名称

mysql - 无法从查询中获取适当的值?

python - 我如何知道在执行 cursor.execute() 时查询是否正确执行?

postgresql - 并发刷新物化 View

mysql - 选择每个测验的最佳分数和积分排行榜

Mysql UNION 和 GROUP BY

sql - T-SQL 按另一个表中的父键进行分组

sql - PostgreSQL 触发器函数获取堆栈并且不更新表

mysql - having子句不过滤记录mysql

ruby-on-rails - Hstore 和 Multi-Tenancy