PostgreSQL – How to Find Matching Pairs Inside Table

postgresql

I have a table where I store logs in Postgres. These logs contain data for cases and the case number. Each row store the case number and more records.

Example:

+-----------------+-----------+---------+------+------+
| case number     | action_id | task_id | user | date |
+-----------------+-----------+---------+------+------+
| 14221/2018/FILE | 1         | 7       |      |      |
+-----------------+-----------+---------+------+------+
| 23456/2018/FILE | 1         | 7       |      |      |
+-----------------+-----------+---------+------+------+
| 14221/2018/FILE | 2         | 7       |      |      |
+-----------------+-----------+---------+------+------+
| 14221/2018/FILE | 1         | 6       |      |      |
+-----------------+-----------+---------+------+------+
| 24556/2018/FILE | 1         | 7       |      |      |
+-----------------+-----------+---------+------+------+
| 34567/2018/FILE | 1         | 7       |      |      |
+-----------------+-----------+---------+------+------+
| 24556/2018/FILE | 1         | 6       |      |      |
+-----------------+-----------+---------+------+------+

I'd like to create a query where the result is all the row where task_id = 7, but only contain those where case number has no action_id=2 pair.

Example result:

+-----------------+-----------+---------+------+------+
| case number     | action_id | task_id | user | date |
+-----------------+-----------+---------+------+------+
| 23456/2018/FILE | 1         | 7       |      |      |
+-----------------+-----------+---------+------+------+
| 24556/2018/FILE | 1         | 7       |      |      |
+-----------------+-----------+---------+------+------+
| 34567/2018/FILE | 1         | 7       |      |      |
+-----------------+-----------+---------+------+------+

I have to make report from the log but I don't know how to perform this query.

Best Answer

How about this (untested)?

select *
from log_table x
where task_id = 7
and not exists (
  select 1
  from log_table
  where case_number = x.case_number
  and task_id = x.task_id
  and action_id = 2
);