4212extra
4212extra

Reputation: 81

SQL Query to count between range of minimum date and date in other column

       temp
|id|received  |changed   |
|33|2019-02-18|2019-11-18|
|33|2019-08-02|2019-11-18|
|33|2019-12-27|2019-11-18|
|18|2019-07-14|2019-10-18|
|50|2019-03-20|2019-05-26|
|50|2019-01-19|2019-05-26|

The 'temp' table shows users who received a request for an activity. A user can make multiple requests. Hence the received column has multiple dates showing when the requests was received. The 'changed' table shows when the status was changed. Hence there will be only 1 value per user for 'changed'. Need to find the COUNT of requests per user BETWEEN the MIN(received) date and the date when the status was changed.

The expected result should look like this :- The third row of id- 33 should not be selected because the received date is after the changed date.

|id|total_requests_sent|
|33|2                  |
|18|1                  |
|50|2                  |


I have tried to add an additional column with the MIN(received) date per user. Can't figure how to get the range part.

Select * 
from temp
INNER JOIN (
Select temp.id, MIN(temp.received) MinDate
From temp
group by temp.id
) t ON temp.id =t.id AND temp.received = t.MinDate

```

Upvotes: 0

Views: 417

Answers (2)

Gary
Gary

Reputation: 899

This will work for you:

select id, count(days) as total_requests_sent 
from
(select id, (changed - received) as days
from temp1) as foo
where days >0
group by id;

The logic here is subtracting the two days, and counting the number of days where the values are positive (i.e, received > changed).

Ouput:

id total_requests_sent
50  2
18  1
33  2

EDIT

I only checked the other part of your question now! If you want to include a minimum received date per user too, then use this code:

select id, count(days) as total_requests_sent, min(received) min_received
from
(select id, date_part('day',changed - received) as days,received
from temp1
where changed >= received) as foo
group by id;

Output:

id total_requests_sent min_received
33  2                  2019-02-18
18  1                  2019-07-14
50  2                  2019-01-19

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269963

I think this is simple aggregation:

select id,
       count(*) filter (where received < changed) as total_requests_sent
from temp
group by id;

If you know that there is at least one "received" for each user, move the condition to the where clause:

select id,
       count(*) as total_requests_sent
from temp
where received < changed
group by id;

Upvotes: 1

Related Questions