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

旧城冷巷雨未停 提交于 2021-01-29 19:50:45

问题


       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

```

回答1:


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;



回答2:


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


来源:https://stackoverflow.com/questions/60211659/sql-query-to-count-between-range-of-minimum-date-and-date-in-other-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!