首页 > 解决方案 > 如何使用 4tables 中的 case 语句连接 postgres sql 中的行

问题描述

emp_id   project_id  TASK_11     TASK_12     TASK_13    TASK_14
42527     4           no         no          no         yes
42527     4           no         yes         no         no
42527     4           yes        no          no         no
42527     4            no        no         yes         no

在上表中,我想显示所有 emp_id 都需要来一次。方法

emp_id   project_id  TASK_11     TASK_12     TASK_13    TASK_14
42527     4           yes        yes         yes            yes

我想像这样使用下面的命令显示请让我知道需要修改的地方

select distinct(b.emp_id),c.project_id,
(CASE when task_id='11' then 'yes'
    else 'no'
END) as "TASK_11",
(CASE 
    when task_id='12' then 'yes'
else 'no'
END) as "TASK_12",
(CASE 
    when task_id='13' then 'yes'
    else 'no'
END) as "TASK_13",
(CASE 
    when task_id='14' then 'yes'
    else 'no'
end) as "TASK_14"
FROM "Projects".user_projects a,
    "Projects".user_clients b,
    "Projects".project_tasks c,
    "Projects".user_tasks d,
    "Projects".projects e
WHERE  c.id = d.id AND a.id = b.id AND e.client_id=b.client_id 
    AND a.project_id=c.project_id and b.client_id=e.client_id
    and(b.emp_id = ANY (ARRAY[45262, 42572, 42527, 40904, 808, 909, 109, 
        147, 70707, 41111, 41041, 80808, 4235, 22, 428882, 4001100,
        40904, 42527, 42581, 42581, 12, 12, 42501, 42501, 202, 47100,
        42501, 4001100, 6389, 20240, 11662, 23556, 30480])) 
    AND e.project_name = 'wms' and c.project_id=4

标签: sqlpostgresqlgreatest-n-per-group

解决方案


您可以使用 bool_or() 和 bool_and() 聚合布尔值

在您的情况下,您应该使用 bool_or()

select emp_id, project_id, 
       bool_or(TASK_11) task_11,
       bool_or(TASK_11) task_12,
       bool_or(TASK_11) task_13,
       bool_or(TASK_11) task_14
  from "your_query"
 group by emp_id, project_id

顺便提一句。您的查询在少数地方似乎不正确。首先是不同的(如 Raymond Nijland 和 a_horse_with_no_name),这部分看起来很奇怪“c.id = d.id AND a.id = b.id”,直到 id 实际上是 user_id。


推荐阅读