Search code examples
postgresqlif-statementsubqueryaliassql-like

Postgresql like into if clause


I got this PostgreSQL query:

SELECT Sum(CASE 
                 WHEN p LIKE '%add%' 
                      AND p NOT LIKE '%add post%' THEN counter 
                 ELSE 0 
               end) AS "AGREGAR",
          Sum(IF p LIKE '%add%' AND p NOT LIKE '%add post%' THEN 1 ELSE 0 END IF ) AS P 
    FROM   (SELECT l.action AS p,
                   Count(l.userid) AS counter
                   --r.name 
            FROM   mdl_log AS l 
                   JOIN mdl_role_assignments AS ra 
                     ON l.userid = ra.userid 
                   JOIN mdl_role AS r 
                     ON ra.roleid = r.id 
                   JOIN mdl_course AS c 
                     ON c.id = l.course 
                        AND course = 12033 
                        AND roleid = 3 
            GROUP  BY roleid, 
                      l.action, 
                      r.name 
            ORDER  BY l.action) AS "P"

But when i execute it, i get this error:

ERROR:  error de sintaxis en o cerca de «p»
LINE 6:               Sum(IF p LIKE '%add%' AND p NOT LIKE '%add pos...
                             ^
********** Error **********

ERROR: error de sintaxis en o cerca de «p»
SQL state: 42601
Character: 216

It's like if the engine don't recognise the "p" alias in the sub-query, but when I put "p" without anymore in the select, it works fine. What am I doing wrong?


Solution

  • Change the line with the if conditional to a normal case expression:

    Sum(CASE WHEN p LIKE '%add%' AND p NOT LIKE '%add post%' THEN 1 ELSE 0 END) AS P 
    

    and you should be fine. The if statement is used in the PL/pgSQL language used in functions and triggers etc.