1

I'm trying to get a total count of results from a query. Its a bit difficult for me to explain, but what I want to do is something like : get a count for each of the results from my select statement that matches my where statement.

SELECT  
users_profiles.account_num,
cases_visits.patient_visit_type,
select max (cases_visits.created_dt)
FROM `users_profiles`
join cases on cases.doctor_id = users_profiles.user_id
join cases_visits on cases_visits.case_id = cases.id
where cases_visits.patient_visit_type = 'NP'

The above statement gives me all the data I need, but each 'users_profiles.account_num' will have several matching 'NP' results, rather than just counting the amount of 'NP' results each 'users_profiles_account_num' have, they would all be returned in rows. I also need to add a select max to get the max NP date to be returned along with the count.

SELECT  
users_profiles.account_num,
count(cases_visits.patient_visit_type)
FROM `users_profiles`
join cases on cases.doctor_id = users_profiles.user_id
join cases_visits on cases_visits.case_id = cases.id
where cases_visits.patient_visit_type = 'NP'

This query will count all 'NP', but that's all. It will only return one (1) 'users_profiles.account_num' result.

In other words this is what I'm getting :

account_num| patient_visit_type
-------------------------------
12345      |NP
12345      |NP
12345      |NP

And this is what I'm trying to get:

account_num| patient_visit_type| max created_dt
-----------------------------------------------
12345      |3                  |10/20/2020
56746      |7                  |10/20/2020
90000      |15                 |10/20/2020
4

1 回答 1

1

这样的事情肯定会奏效:

SELECT  
users_profiles.account_num,
count(cases_visits.patient_visit_type),
max(cases_visits.created_dt)
FROM `users_profiles`
join cases on cases.doctor_id = users_profiles.user_id
join cases_visits on cases_visits.case_id = cases.id
where cases_visits.patient_visit_type = 'NP'
GROUP BY users_profiles.account_num
于 2013-08-26T17:29:13.717 回答