计算患者(女性和男性)第一次咨询的次数以及随后的咨询次数

Count how many times a patient (women and men) got a consult for first time and how many come subsequently

我有两个 table 是这样的:

Table Pacient
---------------------
id|    name     |sex|
01|    george   |m  |
02|    laura    |f  |
03|    holly    |f  |
04|    bill     |m  |
05|    gene     |m  |
06|    elizabeth|f  | 
---------------------

Table Consulting
------------------------
id|diagnostic|id_pacient
01| random   |01
02| random   |02
03| random   |04
04| random   |01
05| random   |04
06| random   |03
07| random   |06
08| random   |05
09| random   |03
------------------------

我喜欢这样显示 table:

-------------------------
sex|subsequent|first_time
m  |4         | 1
f  |2         | 2
-------------------------

到目前为止,我从自己的数据中得到了这个:

-------------------------
sex|subsequent|first_time
m  |16        | 1(wrong value)
-------------------------

我从这个查询中得到了以上结果:

select
  p.sex,
  count(c.id_pacient) as subsquent, 
  count(distinct c.pacientes_id) as first_time 
from pacient p 
inner join consulting c on p.id=c.id_pacient 
group by c.id_pacient having subsequent > 1;

使用子查询计算每个患者就诊的次数,然后使用案例对不同的列求和:

select
  sex, 
  sum(visits = 1) single_visit, 
  sum(visits > 1) subsequent
from (select p.sex, count(*) as visits
      from pacient p
      join consulting c on p.id=c.id_pacient
      group by c.id_pacient) x

在mysql中可以用sum(condition)来统计有多少次为真,因为真为1,假为0。


为确保两种性别都在输出中表示,对包含两种性别值的行集使用左连接:

select
  s.sex, 
  sum(visits = 1) single_visit, 
  sum(visits > 1) subsequent
from (select 'm' sex union select 'f') s
left join (select p.sex, count(*) as visits
      from pacient p
      join consulting c on p.id=c.id_pacient
      group by c.id_pacient) v
    on v.sex = s.sex