0

假设有一个表assignments,它的列是

  • assignment_id
  • 转让人
  • task_id
  • 受让人

分配者可以将相同的 task_id 分配给多个受让人。目前,我有一个分配给 2 名分配者的任务。让我们在下表中查看我的示例:

+---------------+----------+---------+----------+
| assignment_id | assignor | task_id | assignee | 
+---------------+--------------------+----------+
|       1       |    a1    |    t1   |    x1    | 
+---------------+----------+---------+----------+
|       2       |    a1    |    t1   |    x2    | 
+---------------+----------+---------+----------+

当转让人移除受让人时,表格如下所示:

+---------------+----------+---------+----------+
| assignment_id | assignor | task_id | assignee | 
+---------------+--------------------+----------+
|       1       |    a1    |    t1   |    x1    | 
+---------------+----------+---------+----------+
|       2       |    a1    |    t1   |   null   | 
+---------------+----------+---------+----------+

现在,我需要一个查询,该查询仅在此特定 task_id 的每条记录在受理人列中具有空值时才返回 true。到目前为止我写的:

SELECT DISTINCT task_id, nulls, total,

    (CASE
        WHEN nulls = total then true
        ELSE false
    END) unassigned
    
FROM

(
SELECT task_id, 
(SELECT count(*) FROM assignments b WHERE assignee IS NULL AND b.task_id = a.task_id) 'nulls',
(SELECT count(*) FROM assignments b WHERE b.task_id = a.task_id) 'total'

FROM assignments a 

WHERE assignee is NULL) c

结果是:

+--------------------------------------+
| task_id | nulls | total | unassigned | 
+--------------------------------------+
|    1    |   2   |   2   |     1      | 
+---------+-------+-------+------------+

关于改进我的查询或完全替换它的任何建议?

4

2 回答 2

0

如果我正确地跟随你,你可以只使用聚合:

select assignment_id,
    count(*) - count(assignee) as nulls,
    count(*) as total,
    case when count(assignee) = 0 then 1 else 0 end as unassigned
from assignments
group by assignment_id

如果要过滤未分配的分配,则可以having在查询末尾添加一个子句:

having count(assignee) = 0
于 2020-09-16T13:46:14.240 回答
0

我认为您只需要 2 列:task_idnulls in的行数assignee
所以group by taskid并在having子句中设置条件:

select task_id, count(*) total
from assignments
group by task_id
having max(assignee) is null

该条件having max(assignee) is null仅返回列taskid中只有nulls 的 s assignee

于 2020-09-16T13:46:45.857 回答