Mysql计数结果没有重复

时间:2013-08-26 17:18:08

标签: mysql

我正在尝试从查询中获取结果总数。我有点难以解释,但我想要做的是:从我的select语句中得到与我的where语句匹配的每个结果的计数。

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'

以上陈述为我​​提供了我需要的所有数据,但每个'users_profiles.account_num'都会有几个匹配的'NP'结果,而不是仅计算每个'users_profiles_account_num'的'NP'结果的数量,它们都会按行返回。我还需要添加一个select max来获取与计数一起返回的最大NP日期。

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'

此查询将统计所有“NP”,但这就是全部。它只返回一(1)个'users_profiles.account_num'结果。

换句话说,这就是我得到的:

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

这就是我想要的:

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

1 个答案:

答案 0 :(得分: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
相关问题