I have two tables. One is Contact Registration table and one is Payments table One contact registration can have multiple payments. eg: 1 CR can have 15 payments
ContactRegId | RegStatus | RenewalStatus | ExpiryDate |
---|---|---|---|
123456 | Suspended | Pending | 2023-02-15 |
2345678 | Suspended | Complet | 2023-01-03 |
758948 | Registerd | Pending | 2023-02-15 |
3134232 | notregstd | Pending | 2023-01-03 |
435345 | Registerd | Pending | 2023-02-15 |
5636443 | notregstd | Pending | 2023-01-03 |
ContactRegId | CreatedOn | PaymentId |
---|---|---|
123456 | 2021-05-10 | 43 |
123456 | 2020-09-11 | 42 |
123456 | 2019-03-30 | 21 |
123456 | 2018-12-10 | 46 |
758948 | 2022-09-14 | 24 |
758948 | 2021-08-17 | 423 |
758948 | 2020-07-03 | 432 |
758948 | 2019-06-23 | 437 |
758948 | 2018-09-15 | 138 |
435345 | 2022-09-11 | 2345 |
435345 | 2021-08-01 | 4234 |
435345 | 2020-07-12 | 436 |
435345 | 2019-04-14 | 438 |
435345 | 2018-01-16 | 433 |
I need the Contact Registration records which satisfies (RegStatus = Suspended or registered) and RenewalStatus = Pending from Contact registration table and if the payments are not created this year
So the output should be
ContactRegId | RegStatus | RenewalStatus | ExpiryDate |
---|---|---|---|
123456 | Suspended | Pending | 2023-02-15 |
How to do this?
I tried using below query. But it didn't work.
select distinct cr.ContactRegId , COUNT(PaymentId) as count1
from contactregistration cr left join payments p
on cr.ContactRegId = p.ContactRegId
where (cr.RegStatus = 'Registerd' or cr.RegStatus = 'Suspended')
and cr.RenewalStatus = 'Pending'
and YEAR(p.CreatedOn) = YEAR(getdate())
group by cr.ContactRegId having COUNT(PaymentId) = 0
CodePudding user response:
I need the Contact Registration records which satisfies (RegStatus = Suspended or registered ) and RenewalStatus = Pending from Contact registration table and if the payments are not created this year
You can filter the registration table with a subquery that ensures that the contact had no payment this year:
select r.*
from contactRegistration r
where r.RegStatus in ('Suspended', 'Registered')
and r.RenewalStatus = 'Pending'
and not exists (
select 1
from payments p
where
p.ContactRegId = r.ContactRegId
and p.CreatedOn >= datefromparts(year(getdate()), 1, 1)
)