问题
I am using Microsoft SQL SERVER 2014.
The following is my query
SELECT type, SUM(calories) AS total_calories
FROM exercise_logs
GROUP BY type
HAVING total_calories > 150;
and I get the error
Msg 207, Level 16, State 1, Line 2 Invalid column name 'total_calories'.
it is a very simple table (I am new to sql and learning it). can somebody point out what am i doing wrong? Thanks.
回答1:
Aggregation
is required , as you have no access to alias total_calories
SELECT type,SUM(calories) AS total_calories
FROM exercise_logs
GROUP BY type
HAVING SUM(calories) > 150;
回答2:
You can also wrap the GROUP BY
query up in a derived table:
select type, total_calories
(
SELECT type, SUM(calories) AS total_calories
FROM exercise_logs
GROUP BY type
) dt
WHERE total_calories > 150
回答3:
You need the aggregate function in the HAVING
:
SELECT type
, SUM(calories) AS total_calories
FROM exercise_logs
GROUP BY type
HAVING SUM(calories) > 150;
回答4:
The 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
来源:https://stackoverflow.com/questions/34741289/invalid-column-name-while-using-the-having