It sounds so simple but I can't figure it out. I have 2 tables:
TABLE 1 contains a list of projects with the dates at which they were approved.
PROJECT | APPROVAL_DATE |
---|---|
A | 12/06/2019 |
A | 01/09/2020 |
A | 05/08/2021 |
A | 07/12/2021 |
B | 01/05/2018 |
B | 06/09/2019 |
B | 12/23/2020 |
TABLE 2 contains dates when tests were performed on these projects.
PROJECT | TEST_DATE |
---|---|
A | 01/06/2019 |
A | 01/07/2019 |
A | 02/21/2019 |
... | ... |
A | 06/22/2021 |
... | ... |
B | 01/12/2021 |
... | ... |
THIS IS WHAT I NEED: For each project, I want to count the total number of tests prior to each APPROVAL_DATE, so I would have this:
PROJECT | APPROVAL_DATE | TOTAL_TESTS_BEFORE_APPROVAL_DATE |
---|---|---|
A | 12/06/2019 | 1264 |
A | 01/09/2020 | 1568 |
A | 05/08/2021 | 1826 |
A | 07/12/2021 | 2209 |
B | 01/05/2018 | 560 |
B | 06/09/2019 | 790 |
B | 12/23/2020 | 1560 |
CodePudding user response:
You could do it like this using a subquery https://prestodb.io/docs/current/sql/select.html
select PROJECT, APPROVAL_DATE,
(
select COUNT(*)
from TABLE2
where TABLE1.PROJECT = TABLE2.PROJECT
and TABLE2.TEST_DATE <= TABLE1.APPROVAL_DATE
) TOTAL_TESTS_BEFORE_APPROVAL_DATE
FROM TABLE1
CodePudding user response:
here is how you can do it using left join :
select t1.project, t1.APPROVAL_DATE, count(t2.test_date) TOTAL_TESTS_BEFORE_APPROVAL_DATE
from table1 t1
left join table2 t2
on t1.project = t2.project
and t1.APPROVAL_DATE > t2.TEST_DATE
group by t1.project, t1.APPROVAL_DATE