问题
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