我有3个表:OpportunityContact,TaskContact和Tasks。
关系 机会有很多任务。联系人可以分配给许多任务。一个机会有很多联系人。
相关表格
task:
-----
id
status
opportunity_id
task_contact
-----
task_id
contact_id
opportunity_contact
-----
opportunity_id
contact_id
问题: 在给定contact_id的情况下,我也想确定向该联系人分配的任务,并计算分配给他们的每个任务的状态。
示例:
我希望我的SQL结果产生以下结果。
| contact_id | opportunity_id | total_tasks_count | tasks_in_progress_count | tasks_in_review_count |tasks_completed_count |
|--------------------------------------------------------------------------------------------------------------------------
| 1 | 1 | 1 | 1 | 0 |0 |
| -------------------------------------------------------------------------------------------------------------------------
| 1 | 2 | 0 | 0 | 0 |0 |
我尝试过的SQL:
SELECT distinct
ocr.contact_id,
ocr.opportunity_id,
task.status,
sum(case when task.status is NOT NULL then 1 else 0 end) total_tasks_count,
sum(case when task.status = 'In Progress' then 1 else 0 end) tasks_in_progress_count,
sum(case when task.status = 'In Review' then 1 else 0 end) tasks_in_review_count,
sum(case when task.status = 'Completed' then 1 else 0 end) tasks_completed_count
FROM opportunity_contact ocr
LEFT JOIN task ON ocr.opportunity_id = task.opportunity_id
LEFT JOIN task_contact tc ON task.id = tc.task_id
WHERE
ocr.contact_id = '1'
GROUP BY
ocr.opportunity_id,
task.status,
ocr.contact_id;
我得到的结果:
| contact_id | opportunity_id | total_tasks_count | tasks_in_progress_count | tasks_in_review_count |tasks_completed_count |
|--------------------------------------------------------------------------------------------------------------------------
| 1 | 1 | 25 | 25 | 0 |0 |
| --------------------------------------------------------------------------------------------------------------------------
| 1 | 2 | 24 | 24 | 0 |0 |
当ID = 1的Contact只分配给1个任务时,为什么我的查询计数所有25个任务?!如何获得包含同一联系人未分配任务的其他机会的信息?
请谢谢!
答案 0 :(得分:0)
您在查询中引用opportunity_contact
,但这不是问题说明的一部分。联系人在task_contact
表中,因此足以进行过滤:
SELECT ocr.contact_id, task.task_id,
count(task.status) as total_tasks_count,
sum( (task.status = 'In Progress')::int) as tasks_in_progress_count,
sum( (task.status = 'In Review')::int) as tasks_in_review_count,
sum( (task.status = 'Completed')::int as tasks_completed_count
FROM task JOIN
task_contact tc
ON task.id = tc.task_id
WHERE tc.contact_id = '1'
GROUP BY ocr.contact_id, task.id;