And*_*ena 57 sql sql-server alias
我想知道为什么我不能在count(*)中使用别名并在having子句中引用它.例如:
select Store_id as StoreId, count(*) as _count
from StoreProduct
group by Store_id
having _count > 0
Run Code Online (Sandbox Code Playgroud)
不会工作..但如果我删除_count并使用count(*)代替它.
mar*_*ton 94
见引用文档通过CodeByMoonlight在回答对你最近的问题.
在SELECT之前评估HAVING子句 - 因此服务器还不知道该别名.
- 首先,形成from子句中所有表的乘积.
- 在那里,然后条款进行评估,以消除不符合search_condition行.
- 接下来,使用group by子句中的列对行进行分组.
- 然后,消除不满足having子句中的search_condition的组.
- 接下来,将评估select子句目标列表中的表达式.
- 如果select子句中存在distinct关键字,则现在会删除重复的行.
- 该联盟是各个子选择进行评估后作出.
- 最后,生成的行根据order by子句中指定的列进行排序.
Sha*_*nce 12
该select子句是逻辑上执行的最后一个子句,除了order by.该having子句在select之前发生,因此别名尚不可用.
如果你真的想使用别名,而不是我建议这样做,可以使用内嵌视图来使别名可用:
select StoreId, _count
from (select Store_id as StoreId, count(*) as _count
from StoreProduct
group by Store_id) T
where _count > 0
Run Code Online (Sandbox Code Playgroud)
或者在SQL Server 2005及更高版本中,CTE:
; with T as (select Store_id as StoreId, count(*) as _count
from StoreProduct
group by Store_id)
select StoreId, _count
from T
where _count > 0
Run Code Online (Sandbox Code Playgroud)
您可以在 select 子句中使用 count 的别名,但不能在having 语句中使用它,所以这可以工作
select Store_id as StoreId, count(*) as _count
from StoreProduct
group by Store_id
having count(*) > 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67799 次 |
| 最近记录: |