Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL - Aliases column and HAVING

SELECT  
CASE WHEN SUM(X.Count)*3600 is null THEN  '0'  
            ELSE  
            SUM(X.Count)*3600  
       END AS PJZ,  
       X.Mass  
FROM X  
WHERE X.Mass > 2000  
HAVING ((X.Mass / PJZ * 100) - 100) >= 10;

Getting: ERROR: Column »pjz« doesn't exists.

How can I do something like this?

like image 781
6EQUJ5HD209458b Avatar asked Sep 22 '11 07:09

6EQUJ5HD209458b


People also ask

Can we use alias in HAVING clause?

A column alias cannot be used in a SELECT, WHERE, GROUP BY or HAVING clause due to the order of execution. You must refer to the original column name.

Is it mandatory for alias of a column to have a name different than the name of column being aliased?

There is no need to alias a column name unless you are changing it to something besides what the column name in the database is. Will both return the same column names to the end user so in this case there is no need to add the alias as it will have no impact on the returned results or column names.

Why would you column use aliases?

SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used to make column names more readable. An alias only exists for the duration of that query.

Are column aliases allowed in JOIN conditions?

No, you cannot do that. The alias is not bound until later in the processing. You can use "Nombre" in an ORDER BY, but not in a WHERE clause and certainly not in a JOIN clause.


1 Answers

You can't use aliases in a having, and have to duplicate the statement in the having cluause. Since you only want to check for null, you could do this:

SELECT coalesce(SUM(X.Count)*3600, 0) AS PJZ, X.Mass
FROM X
WHERE X.Mass > 2000
HAVING ((X.Mass / coalesce(SUM(X.Count)*3600, 0) * 100) - 100) >= 10; 
like image 104
jishi Avatar answered Sep 28 '22 13:09

jishi