如何在postgresql查询中放置嵌套的case-when条件

时间:2016-11-24 05:11:10

标签: postgresql if-statement nested case-when

我想在查询条件时写入嵌套大小写,以便存储将来自一个案例的条件和条件转换为同一个新列时的另一个案例。得到这种结果我写的查询为:

(case when sq_name_new1 like format('%%%s%%',demo.name) THEN count(sq_name_new1) else (when demo.empcode is not null then count(demo.id) End) END) AS indivisual from res_scheduledjobs

在上面的查询demo.name列来自CTE.so我的整个查询看起来像:

with demo(empcode,id,name) as               
(select hr_employee.emp_code,hr_employee.id,concat(resource_resource.name,' ',hr_employee.middle_name,' ',hr_employee.last_name) as name from hr_employee inner join  resource_resource on resource_resource.id=hr_employee.resource_id)
select demo.empcode,demo.name,sq_name_new1,(case when sq_name_new1 like format('%%%s%%',demo.name) THEN count(sq_name_new1) else (when demo.empcode is not null then count(demo.id) End) END) AS indivisual from res_scheduledjobs LEFT JOIN demo on demo.id=res_scheduledjobs.assigned_technician group by res_scheduledjobs.assigned_technician,sq_name_new1,demo.empcode,demo.name ;

我只想将(sq_name_new1)列的计数存储到INDIVISUAL列中,并将(demo.id)列的计数存储到同一列中,即如果第一种情况不匹配,则在INDIVISUAL中。 但是当我执行我的查询时,它会抛出一个错误。也就是说,条件语法时出现错误。

请帮我写出正确的嵌套case-when条件。

2 个答案:

答案 0 :(得分:9)

CASE ... WHEN ... END是一个表达式。它可以像任何其他表达式一样嵌套。

CASE
     WHEN condition THEN
         CASE
             WHEN othercondition THEN
                 ....
         END
END

答案 1 :(得分:1)

第一个分号;应该像@Craig Ringer的答案一样被移除。

SELECT 
  CASE WHEN condition1 THEN
    CASE
      WHEN condition1.1 THEN
        ...
    END
  END AS column_name
FROM table_name;