SQL Server 关键字

SQL Server (Transact-SQL) AS 关键字在 ALIAS 语句中使用,用于为表的列、聚合函数列或表本身提供临时名称。别名仅在查询期间存在。它有助于轻松理解名称,从而提高 SQL Server 代码的可读性。

语法

在 SQL Server (Transact-SQL) 中使用 AS 关键字的语法如下:

/* 列的别名 */
SELECT column_name AS alias_name
FROM table_name;

/* 聚合函数的别名 */
SELECT SUM(column_name) AS alias_name
FROM table_name
WHERE condition(s);

/* 表的别名 */
SELECT alias_name_1.column1, alias_name_2.column1, ...
FROM table1 AS alias_name_1
INNER JOIN table2 AS alias_name_2
ON alias_name_1.matching_column = alias_name_2.matching_column; 

示例:

考虑一个数据库,其中包含名为 Employee 和 Contact_Info 的表,并具有以下记录:

表 1:Employee 

EmpIDNameCityAgeSalary
1JohnLondon253000
2MarryNew York242750
3JoParis272800
4KimAmsterdam303100
5RameshNew Delhi283000
6HuangBeijing282800

表 2:Contact_Info 表

Phone_NumberEmpIDAddressGender
+1-80540980002Brooklyn, New York, USAF
+33-1479961013Grenelle, Paris, FranceM
+31-2011503194Geuzenveld, Amsterdam, NetherlandsF
+86-10997324586Yizhuangzhen, Beijing, ChinaM
+65-672348247Yishun, SingaporeM
+81-3577990728Koto City, Tokyo, JapanM

带列的别名:下面提到的查询用于创建别名列 - Employee 表的 name 和 City。

SELECT Name AS [Employee Name], Age AS [Employee Age], City 
FROM Employee; 

这将产生如下结果如下所示:

Employee NameEmployee AgeCity
John25London
Marry24New York
Jo27Paris
Kim30Amsterdam
Ramesh28New Delhi
Huang28Beijing

具有聚合函数的别名:以下查询用于获取年龄大于 27 岁的员工数量。

SELECT COUNT(Name) AS [Number of Employees]
FROM Employee
WHERE Age > 27; 

这将带来以下结果:

Number of Employees
3

带有表的别名:要内连接 Employee和Contact_Info表基于匹配列EmpID,语句如下。执行两个表的内连接时,会使用表的别名。

SELECT A.Name, A.Age, B.Address 
FROM Employee AS A
INNER JOIN Contact_Info AS B
ON A.EmpID = B.EmpID; 

上述查询的结果将是:

NameAgeAddress
Marry24Brooklyn, New York, USA
Jo27Grenelle, Paris, France
Kim30Geuzenveld, Amsterdam, Netherlands
Huang28Yizhuangzhen, Beijing, China