为什么您可以按“ as”语句排序但不能按“ as”语句分组

时间:2019-09-26 02:12:02

标签: sql

Select
Substr(creationtime,0,10) as dt,
Count(1) as num
From comment
Group by dt 
Order by num desc

它显示dt错误

3 个答案:

答案 0 :(得分:1)

逻辑查询处理顺序就是答案。

FROM clause
JOIN clause,ON clause,APPLY clause
WHERE clause
GROUP BY clause and AGGREGATE Functions
CUBE | ROLLUP | GROUPING SETS
HAVING clause
SELECT clause,UNION clause
DISTINCT clause
ORDER BY clause
TOP clause
OFFSET/FETCH
FOR XML 

在发生SELECT时将分配别名(“ as”),但是根据逻辑处理顺序,GROUP BY在SELECT之前起作用。因此,GROUP BY不知道您提供的别名。 但是ORDER BY在SELECT之后起作用。因此,ORDER BY知道您提供的别名。

希望您现在知道了。

因此,按照逻辑处理顺序,实际查询可以如下:

Select
Substr(creationtime,0,10) as dt,
Count(1) as num
From comment
Group by (Substr(creationtime,0,10)) 
Order by num desc

还为ref添加了物理(书写)查询过程顺序,

SELECT 
DISTINCT 
<column-list>
FROM 
<left_table>
<join_type> 
JOIN 
<right_table>
ON 
<join_condition>
WHERE 
<where_condition>
GROUP BY 
<group_by_list>
HAVING 
<having_condition>
ORDER BY 
<order_by_list>

答案 1 :(得分:0)

之所以不能按列别名(“ as”语句)进行分组,是因为SQL查询各部分的执行顺序不允许这样做。 GROUP BY子句在SELECT之前执行,因此无法访问列别名,因为尚未创建它们。 SELECT之后执行ORDER BY,因此别名可用。

这已经被要求在这里回答:SQL - using alias in Group By

此外,可以在此处找到更多信息:https://sqlbolt.com/lesson/select_queries_order_of_execution

答案 2 :(得分:0)

您可以为此使用子查询

Select
c2.dt as dt,
c2.num as num
From comment c1
INNER JOIN (SELECT Substr(creationtime,0,10) as dt, Count(1) as num) c2 ON c2.ID = c1.ID
Group by c2.dt
Order by num desc