(T-SQL) Why does this subquery need an alias?

北慕城南 提交于 2021-02-10 16:17:34

问题


SELECT 
*

FROM

 (SELECT 
    ROW_NUMBER() OVER (PARTITION BY a.vendorid ORDER BY a.CreatedDateUTC) as RowNum
    ,*

 FROM 
    ZpVendors_Kim.dbo.VendorPaymentAcceptanceAudit a) Needs_Alias_Here

 WHERE 
    RowNum = 1

Very simple query, just wondering - why is an alias needed for it to work?


回答1:


The alias after the subquery (or derived table, if you prefer) is required by SQL Server. It is not only a requirement but a really good idea. In general, column references should be qualified, meaning that they include a table alias. Without an alias, references to columns in the subquery could not be qualified. I think that's a bad thing.

SQL Server is not the only database that requires the alias. MySQL and Postgres (and hence most Postgres-derived databases) do as well. Oracle and SQLite do not. Nor does Google's BigQuery.

I do not know if the alias is an ANSI/ISO requirement. However, I always use one, regardless of the database.




回答2:


every subquery in the FROM need to have alias name in SQL

You have to define so you can add further constraints to your query. otherwise, your DB Engine willn't know how to refer to the subquery.

We can think of the subquery result as a new table, but this table has no name, so give him an alias.



来源:https://stackoverflow.com/questions/52616939/t-sql-why-does-this-subquery-need-an-alias

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!