SQL:在同一select语句中使用函数中列的别名

时间:2010-10-26 08:32:30

标签: sql

我只是想简化一个Select语句:

Select (a+b+c)/3 AS V, MIN((a+b+c)/3) as Min, MAX((a+b+c)/3) as Max from ....

是否有一种干净的方法可以避免在聚合函数中重复该公式(a + b + c)/ 3?

2 个答案:

答案 0 :(得分:10)

SELECT 
  Result/3 AS V, 
  MIN(Result/3) as Min, 
  MAX(Result/3) as Max
FROM
(
  SELECT (a+b+c) AS Result from Table
) AS outerTable

或者甚至

SELECT 
  Result AS V, 
  MIN(Result) as Min, 
  MAX(Result) as Max
FROM
(
  SELECT (a+b+c)/3 AS Result from Table
) AS outerTable

答案 1 :(得分:1)

如果您需要的值不仅仅是一个查询中的(a+b+c)/3而且您的SQL方言支持视图,那么您可能需要考虑使用View。

可以在MySQL中使用以下代码创建包含表MY_TABLE_NAME的所有列的视图+包含值(a+b+c)/3的其他列。

CREATE ALGORITHM = UNDEFINED
SQL SECURITY DEFINER VIEW  `MY_TABLE_NAME_FULL_VIEW` AS
SELECT MY_TABLE_NAME.*, (a+b+c)/3 AS Average
   FROM  `MY_TABLE_NAME`;

可以在MySQL中使用以下代码创建一个仅包含a,b和c列的视图以及包含值(a+b+c)/3的其他列。

CREATE ALGORITHM = UNDEFINED
SQL SECURITY DEFINER VIEW  `MY_TABLE_NAME_LIMITED_VIEW` AS
SELECT a, b, c, (a+b+c)/3 AS Average
   FROM  `MY_TABLE_NAME`;

可以在MySQL中使用以下代码在MySQL中创建仅包含值(a+b+c)/3的视图。

CREATE ALGORITHM = UNDEFINED
SQL SECURITY DEFINER VIEW  `MY_TABLE_NAME_AVERAGE_VIEW` AS
SELECT (a+b+c)/3 AS Average
   FROM  `MY_TABLE_NAME`;

创建视图后,请在选择查询中使用视图而不是表格。


假设您创建了视图MY_TABLE_NAME_AVERAGE_VIEW,则可以将SELECT语句替换为:

SELECT Average AS V, MIN(Average) AS Min, MAX(Average) AS Max
FROM MY_TABLE_NAME_AVERAGE_VIEW;

假设您创建了视图MY_TABLE_NAME_LIMITED_VIEW,并且还需要包含值a,b和C,则可以将SELECT语句替换为:

SELECT a, b, c, Average AS V, MIN(Average) AS Min, MAX(Average) AS Max
FROM MY_TABLE_NAME_LIMITED_VIEW;