MySQL确保输出中存在所有性别

时间:2015-03-24 05:37:17

标签: mysql count group-by output

我的问题是我有两张桌子,我会在一秒钟内给你看,然后我必须打印两种性别,如果第一次是一个pacient vist,那么计数总和为1,如果它的后续计数总和为1,依此类推例如,我有这个虚构的表:

Table Pacient

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

表咨询

------------------------
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
------------------------

到目前为止,我有这个mysql查询:

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

自有数据库的结果:

-------------------------
sex|single_visit|subsequent
m  |24          |2(wrong value)
-------------------------

问题是上面只显示了一个性别,而且其中两个也没有返回打印的后续值是两个性别访问和我最终输出的总和要求的应该是这样的:

请帮助:最终和正确的输出(来自我自己的数据库):

-------------------------
sex|single_visit |subsequent
m  |24           | 1
f  |0            | 1
-------------------------

1 个答案:

答案 0 :(得分:0)

您最后需要添加group by

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
   group by sex