我有两张桌子:
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
------------------------
并且id喜欢显示这样的表:
-------------------------
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;
答案 0 :(得分:0)
使用子查询计算每位患者访问过的次数,然后使用案例对不同的列进行求和:
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)
来计算它的真实次数,因为true为1而false为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