sql - 如何使用 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
解决方案
您可以使用 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。
推荐阅读
- birt - 在 BIRT 中使用 POJO 数据源嵌套表
- mysql - MYSQL 使用连续数值 IF NULL 更新列 - 继续序列
- loops - 弹性搜索循环两个索引的值
- java - 配置映射以连接字符串
- html - 为什么我的网页表单页面没有检测到 CSS 文件?
- sql-server - 如何在 MS SQL Server 中选择 1 周间隔后的 2018 年 7 月日期
- python - Python 中的均值过滤(手动)
- java - 识别 java POJO 类中更改的字段
- vba - 加入具有相同字段的各种表,但表名中的前缀发生变化
- r - 开发连续时间马尔可夫链模型来模拟 R 中鱼身上寄生虫的分布(计数)