将两个已在CASE语句上计算的列相乘

时间:2013-03-15 16:39:50

标签: 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,我会收到语法错误。

2 个答案:

答案 0 :(得分:4)

你可以随时使用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

答案 1 :(得分:2)

CTE是一种有效的方法,提供了额外的选择 对于像这样的简单情况,普通的子查询更简单,速度更快。

SELECT *, (newcol2 * newcol3) AS newcol4
FROM  (
   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) AS newcol3
   FROM  table
   GROUP BY 1, 2
   ) AS sub

BTW:我从newcol3删除了GROUP BY,因为您正在运行聚合函数count(),这有点荒谬。