我正在使用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
,我会收到语法错误。
答案 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()
,这有点荒谬。