How to create a query SQL for Postresql who select only those people who have never participated in previous events and only once this year, as in the last table below.
tbl_evt
id_evt | evt_date |
---|---|
1 | 2022-10-01 |
2 | 2022-08-05 |
3 | 2021-01-01 |
4 | 2020-06-05 |
tbl_people_evt
id_people | id_evt |
---|---|
1 | 1 |
1 | 4 |
2 | 1 |
3 | 1 |
3 | 3 |
4 | 1 |
5 | 1 |
5 | 2 |
6 | 3 |
Searched result
id_people |
---|
2 |
4 |
5 |
4
Answers
I got it, but if anyone has another solution
So if "only those people who have never participated in previous events and only once this year" means
Then
Gives you attended event counts in 2022 and pre-2022 per
id_people
:If you only need
id_people
,Result:
You could use the filtered count function as the following:
And if you want to get only the count of people who match the criteria:
See demo
You can aggregate the data by people ID and use a
HAVING
clause to only get people whose first entry is in the current year:Your description doesn’t match your example. In your description you want people to appear "only once this year", in your example you don’t. Above query is according to your example. If you want to have only one entry in the current year (and provided there can be no future entries), I suggest the following
HAVING
clause instead: