I'm working in PostgreSQL. Suppose I have this Person table:
| id | time | name | type |
----------------------------------------------------
| 1 | 2022-04-25 07:49:58.0 | Brian | Rejection 1 |
| 2 | 2022-04-25 07:49:58.0 | Brian | Rejection 2 |
| 3 | 2022-04-27 13:05:51.0 | Fredd | Rejection 1 |
| 4 | 2022-05-01 02:13:44.0 | Janet | Rejection 1 |
| 5 | 2022-05-01 03:45:06.0 | Janet | Rejection 2 |
| 6 | 2022-05-01 08:01:34.0 | Peter | Approval |
| 7 | 2022-05-01 12:12:53.0 | Frank | Rejection 2 |
| 8 | 2022-05-02 01:26:38.0 | Frank | Approval |
Note: We have 2 rejections types Rejection 1 and Rejection 2.
I would like to make a query that counts the number of Rejections and the number of approvals for each name. However if there are 2 rejections at the same time, for the same name, like the two first rows in the example, it should only count as one.
Let me just add that it's possible for there to be one of each rejection types at the same time for the same name, but it's impossible for there to be two rejections of the same type at the same time for the same name.
So this is what I'm expecting it to return:
| name | approvals | rejections |
----------------------------------
| Brian | 0 | 1 |
| Fredd | 0 | 1 |
| Janet | 0 | 2 |
| Peter | 1 | 0 |
| Frank | 1 | 1 |
The closest I could get to this is the following:
SELECT
name,
COALESCE(SUM(CASE WHEN log_type = 'Approval' THEN 1 ELSE 0 END), 0) approvals,
COALESCE(SUM(CASE WHEN log_type = 'Rejection 1' OR log_type = 'Rejection 2' THEN 1 ELSE 0 END), 0) rejections
FROM
person
GROUP BY
name
The problem with this is that it counts two rejections with same time and name as 2 instead of 1.