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 表
EmpID | Name | City | Age | Salary |
---|---|---|---|---|
1 | John | London | 25 | 3000 |
2 | Marry | New York | 24 | 2750 |
3 | Jo | Paris | 27 | 2800 |
4 | Kim | Amsterdam | 30 | 3100 |
5 | Ramesh | New Delhi | 28 | 3000 |
6 | Huang | Beijing | 28 | 2800 |
表 2:Contact_Info 表
Phone_Number | EmpID | Address | Gender |
---|---|---|---|
+1-8054098000 | 2 | Brooklyn, New York, USA | F |
+33-147996101 | 3 | Grenelle, Paris, France | M |
+31-201150319 | 4 | Geuzenveld, Amsterdam, Netherlands | F |
+86-1099732458 | 6 | Yizhuangzhen, Beijing, China | M |
+65-67234824 | 7 | Yishun, Singapore | M |
+81-357799072 | 8 | Koto City, Tokyo, Japan | M |
带列的别名:下面提到的查询用于创建别名列 - Employee 表的 name 和 City。
SELECT Name AS [Employee Name], Age AS [Employee Age], City
FROM Employee;
这将产生如下结果如下所示:
Employee Name | Employee Age | City |
---|---|---|
John | 25 | London |
Marry | 24 | New York |
Jo | 27 | Paris |
Kim | 30 | Amsterdam |
Ramesh | 28 | New Delhi |
Huang | 28 | Beijing |
具有聚合函数的别名:以下查询用于获取年龄大于 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;
上述查询的结果将是:
Name | Age | Address |
---|---|---|
Marry | 24 | Brooklyn, New York, USA |
Jo | 27 | Grenelle, Paris, France |
Kim | 30 | Geuzenveld, Amsterdam, Netherlands |
Huang | 28 | Yizhuangzhen, Beijing, China |