我正在PostgreSQL中使用如下CASE语句执行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/

10-09 03:08