Postgresql like into if 子句

Postgresql like into if clause

我得到了这个 PostgreSQL 查询:

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"

但是当我执行它时,我得到这个错误:

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

这就像引擎不识别子查询中的 "p" 别名,但是当我在 select 中放入 "p" 时,它工作正常。我究竟做错了什么?

将带有 if 条件的行更改为正常的 case 表达式:

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

你应该没事的。 if语句用于函数和触发器等PL/pgSQL语言