简体   繁体   English

SQL 操作顺序 - GROUP BY 使用在 SELECT 中创建的字段

[英]SQL Order of Operations - GROUP BY using field created in SELECT

I'm having trouble wrapping my head around a fairly elementary concept.我无法围绕一个相当基本的概念进行思考。 Any help appreciated!任何帮助表示赞赏! I have learned from resources like this that the processing order of SQL operations is:我从这样的资源中了解到SQL操作的处理顺序是:

1) from 2) where 3) group by 4) having 5) select 6) order by 7) limit 1) from 2) where 3) group by 4) have 5) select 6) order by 7) limit

However, I am perplexed when looking at this below query taken from DataCamp.但是,在查看来自 DataCamp 的以下查询时,我感到困惑。 If SQL is processing GROUP BY before SELECT, how can I use a field that was created within the SELECT statement (home_team) in the GROUP BY clause?如果 SQL 在 SELECT 之前处理 GROUP BY,我如何使用在 SELECT 语句 (home_team) 中的 GROUP BY 子句中创建的字段?

Thank you!谢谢!

-- Identify the home team as Bayern Munich, Schalke 04, or neither
SELECT 
    CASE WHEN hometeam_id = 10189 THEN 'FC Schalke 04'
        WHEN hometeam_id = 9823 THEN 'FC Bayern Munich'
         ELSE 'Other' END AS home_team,
    COUNT(id) AS total_matches
FROM matches_germany
-- Group by the CASE statement alias
GROUP BY home_team;

Your particular query has:您的特定查询具有:

GROUP BY hometeam_id
---------^

This is a column in the original data, not in the SELECT .这是原始数据中的一列,而不是SELECT The data is aggregated at the hometeam_id level.数据在hometeam_id级别聚合。 Then the CASE expression is applied after the aggregation.然后在聚合之后应用CASE表达式。

Your question supposed that the query is written using:您的问题假设查询是使用以下内容编写的:

GROUP BY home_team

And this might or might not work, depending on the database.这可能会也可能不会起作用,具体取决于数据库。

SQL does not have an "order of processing". SQL 没有“处理顺序”。 The SQL engine analyzes the query and develops a directed-acyclic graph (DAG) representing the operations that need to be performed on the data. SQL 引擎分析查询并开发一个有向无环图 (DAG),表示需要对数据执行的操作。

What you are thinking of are rules for the scoping of identifiers in SQL.您正在考虑的是 SQL 中标识符范围的规则。 The big question is where an alias defined in a SELECT can be used.最大的问题是在哪里可以使用SELECT定义的别名。

Basically no databases allow column aliases to be used in the following clauses:基本上没有数据库允许在以下子句中使用列别名:

  • SELECT
  • FROM
  • WHERE

All databases allow column aliases in the following clauses:所有数据库都允许在以下子句中使用列别名:

  • ORDER BY . ORDER BY

Some databases allow column aliases in the GROUP BY and HAVING clauses.某些数据库允许在GROUP BYHAVING子句中使用列别名。

Your database appears to be one that allows such usage in the GROUP BY .您的数据库似乎允许在GROUP BY中进行此类使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM