PostgreSQL:使用CASE在where子句中添加条件

时间:2016-10-06 10:14:17

标签: postgresql case where-clause

我正在使用PostgreSQL 8.2,我也是PostgreSQL的新手。

我必须在WHERE子句中添加一个条件,具体取决于字段的特定值(49)( activity.type )。这是我的查询:

SELECT activity.*
FROM activity 
LEFT JOIN event_types ON activity.customstatusid = event_types.id, getviewableemployees(3222, NULL) AS report 
WHERE 
( 
    CASE WHEN activity.type = 49 THEN 
    'activity.individualid IN(SELECT individualid from prospects where prospects.individualid = activity.individualid)' 
    ELSE 1 
    END 
)
AND activity.date BETWEEN '2016-10-01' AND '2016-10-06' 
AND activity.type IN (21, 22, 49, 50, 37, 199) 
AND (event_types.status = 1 or event_types.status IS NULL);

当我在PGSQL的命令行访问中运行上面的查询时,我得到以下错误:

ERROR:  invalid input syntax for integer: "activity.individualid IN(SELECT individualid from prospects where prospects.individualid = activity.individualid)"

我在这里缺少什么?

1 个答案:

答案 0 :(得分:3)

将where子句实现为:

WHERE (
    activity.type != 49 OR
    activity.individualid IN (
        SELECT individualid from prospects 
        WHERE prospects.individualid = activity.individualid)
)
AND activity.date BETWEEN '2016-10-01' AND '2016-10-06' 
AND activity.type IN (21, 22, 49, 50, 37, 199) 
AND (event_types.status = 1 or event_types.status IS NULL);

第一个条款只有在以下任何一个情况下才会成立:

  • activity.type != 49;或
  • 在子查询中找到了
  • activity.type == 49activity.individualid