I am given a database with 3 different tables as such, and no sample data:
Basically, I'm trying to find a query for the number of users, for whom the last activity was done with device_name = “phone”
, but who also have at least one additional activity with another device by combining data from the 3 tables.
The issue is that I can't include both those conditions in the same where clause because I'm they should be on different rows, i.e. different activites.
What I have so far is:
With CTE as (
select *
from users u
join activities a on u.user_id=a.activity_user_id
join devices d on a.activity_device_ID=d.device_ID
)
Select count(a.activity_user_id)
from CTE
where (a.activity_is_last='Yes' and d.device_name='phone')
I almost want to include some sort of when clause, so that WHEN the activity is last I want to check if the device is a phone, but when it's not I want to check if it's not phone. I also want to validate that there are at least 2 rows, is_last and not is_last. How is it possible?