我很好奇是否可以使用我在select子句中为其他字段创建的列。
例如,我有这个查询 -
SELECT
users.officeid,
COUNT(DISTINCT CASE WHEN users.active = 1 THEN user.id ELSE NULL END) as active_users,
COUNT(CASE WHEN users.total = 1 THEN 1 ELSE NULL END) as total_users,
active_users / total_users
FROM users
GROUP BY 1
我想要另一列是active_users / total_users,但是我收到了错误 - >
列" active_users"在用户中不存在
我是否需要将它们放在公用表表达式中然后从中进行选择?还有其他解决方案吗?谢谢!
答案 0 :(得分:2)
with cccik as( SELECT
users.officeid,
COUNT(DISTINCT CASE WHEN users.active = 1 THEN user.id ELSE NULL END) as active_users,
COUNT(CASE WHEN users.total = 1 THEN 1 ELSE NULL END) as total_users,
FROM users
GROUP BY 1)
select *, (active_users / total_users) from ccckik
-- you can filter by officeid
-- where officeid = 5
答案 1 :(得分:2)
“As ...”仅重命名查询输出的列。
如果您想在旅途中计算并避免创建其他列,您可以执行以下操作:
select count(column1), count(column1),
count(column1) / count(column2)
from table
您还可以为其创建物化视图。
答案 2 :(得分:1)
这个怎么样?
select officeid, active_users, total_users, active_users / total_users
from
(
SELECT
users.officeid,
COUNT(DISTINCT CASE WHEN users.active = 1 THEN user.id ELSE NULL END) as active_users,
COUNT(CASE WHEN users.total = 1 THEN 1 ELSE NULL END) as total_users
FROM users
GROUP BY 1
)