某些两列按顺序使用别名

Some two columns using alias in order by

我有这个查询:

select 
    id,
    count(1) as "visits",
    count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by "visits", "visitors"

有效。

如果我改成这个

select 
    id,
    count(1) as "visits",
    count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by (("visits") + ("visitors"))

我明白了

column "visits" does not exist

如果我改成 select ID, 计数(1)为 "visits", 计数(不同 visitor_id)作为 "visitors" 来自 my_table 其中时间戳 > '2016-01-14' 按编号分组 按 count(1) + count(distinct visitor_id)

排序

它再次工作。

为什么它对示例 1 和 3 有效,但对示例 2 无效?有什么方法可以使用别名按两列的总和进行排序吗?

我能想到的替代方案:

PS:这个查询是一个玩具查询。真正的要复杂得多。我想在 order by 中重用 select 语句中计算的值,但全部加在一起。

尝试使用实际列而不是使用别名,也尝试将类型更改为 varchar 或 nvarchar,我的意思是:

select 
    id,
    count(1) as "visits",
    count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by (CAST(count(1) AS VARCHAR) + CAST(count(distinct visitor_id) AS VARCHAR))

未定义表达式求值顺序。如果您的 visits + visitors 表达式在别名之前被评估,您将收到上面显示的错误。