'invalid column name' 同时使用 HAVING

'invalid column name' while using the HAVING

我正在使用 Microsoft SQL Server 2014。

以下是我的查询

SELECT type, SUM(calories) AS total_calories
FROM exercise_logs
GROUP BY type
HAVING total_calories > 150;

我得到了错误

Msg 207, Level 16, State 1, Line 2 Invalid column name 'total_calories'.

有人可以指出我做错了什么吗?谢谢

您需要 HAVING 中的聚合函数:

SELECT   type
,        SUM(calories) AS total_calories 
FROM     exercise_logs 
GROUP BY type 
HAVING   SUM(calories) > 150;

Aggregation 是必需的,因为您无权访问别名 total_calories

SELECT   type,SUM(calories) AS total_calories 
FROM     exercise_logs 
GROUP BY type 
HAVING   SUM(calories) > 150;

您还可以将 GROUP BY 查询包装在派生的 table:

select type, total_calories
(
    SELECT type, SUM(calories) AS total_calories
    FROM exercise_logs
    GROUP BY type
) dt
WHERE total_calories > 150

HAVING clause allows you to filter based on the the results of an aggregate function, like SUM, MIN and MAX. You must use these functions directly, unfortunately columns aliases from the SELECT clause cannot be reused here. This is a consequence of the Logical Processing Order. Taken from MSDN:

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.

1.FROM

2.ON

3.JOIN

4.WHERE

5.GROUP BY

6.WITH CUBE or WITH ROLLUP

7.HAVING

8.SELECT

9.DISTINCT

10.ORDER BY

11.TOP