为什么在hading子句中使用别名有效?

时间:2019-06-17 15:41:15

标签: sql sql-server tsql

我在查询中使用group by和hading子句,使用别名似乎一切正常。无论我输入什么值或运算符(<,>),它都将返回正确的结果。根据逻辑查询处理,这应该不起作用,但是可以。另外,即使我在Haven子句中的count函数中放入了一些无意义的字符串,它仍然有效。

我完全感到困惑!

use TSQL2014;
select
c.categoryname,
count(p.productid) as 'TotalProducts'
from Production.Products p

left join Production.Categories c
on p.categoryid = c.categoryid

group by c.categoryname

--having count(p.productid) > 10 
having count('aaaaaa') > 10

order by 'TotalProducts' desc;

2 个答案:

答案 0 :(得分:2)

  

为什么在hading子句中使用别名有效?

'aaaaaa'不是别名,而是字符串文字。

having count('aaaaaa') > 10
-- same as
       count(*)
       count(1) 
       count(GETDATE())

只要表达式不是NULL,那么COUNT就可以正常工作。

答案 1 :(得分:0)

假设您引用的是您发布的代码中当前注释掉的行-p子句中使用了from别名-这意味着您可以在以下任何其他子句中使用它查询-包括子查询,having子句,甚至apply子句和join子句。

select子句中使用别名时,情况并非如此-这些别名只能在order by子句中使用。

select
c.categoryname,
count(p.productid) as 'TotalProducts'
from Production.Products p

left join Production.Categories c

-- both `p` and `c` aliases are valid here since they where introduced in the `from` and `join` clauses
on p.categoryid = c.categoryid

-- the use of `c` here is valid since it was introduced in the `join` clause
group by c.categoryname

-- the use of `p` here is valid since `p` was introduced in the `from` clause.
having count(p.productid) > 10 

-- This, however, will cause an error - invalid column name `TotalProducts`
-- having count(TotalProducts) > 10 

-- This is valid since TotalProducts is an alias introduced in the `select` clause.
order by 'TotalProducts' desc;