GROUP BY分组查询的结果

时间:2019-02-27 20:24:39

标签: mysql sql database

使用的表如下:

CREATE TABLE IF NOT EXISTS planta(
codigo int PRIMARY KEY NOT NULL AUTO_INCREMENT,
especialidad varchar(25) NOT NULL
)ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS habitacion(
id int PRIMARY KEY NOT NULL AUTO_INCREMENT,
numero_camas int NOT NULL,
planta_id int NOT NULL,
FOREIGN KEY (planta_id) REFERENCES planta(codigo)
)ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS paciente(
dni varchar(9) PRIMARY KEY NOT NULL,
num_ss varchar(10) NOT NULL,
nombre varchar(20) NOT NULL,
direccion varchar(50) NOT NULL,
tratamiento mediumtext NOT NULL,
diagnostico mediumtext NOT NULL,
habitacion_id int NOT NULL,
medico_id int NOT NULL,
FOREIGN KEY (habitacion_id) REFERENCES habitacion(id),
FOREIGN KEY (medico_id) REFERENCES medico(num_colegiado)
)ENGINE=InnoDB;

查询是这样的:

SELECT planta.codigo AS Floor_id, habitacion.id AS Room_id, numero_camas - count(dni) AS Free_beds 
FROM habitacion, paciente, planta 
WHERE planta_id = planta.codigo AND habitacion_id = habitacion.id 
GROUP BY planta.codigo, habitacion.id;

它返回以下结果:

Floor id | Room id | Free beds
    1         1          1    
    1         2          1    
    2         3          3

但是我想要这个:

Floor id | Rooms | Free beds
    1        2         2    
    2        1         3    

我认为我有很多问题,因为首先我必须计算每个房间有多少张床(我通过减去房间中的床数减去分配给该房间的人数来做到这一点。) / p>

我想知道是否可以通过当前查询将结果分组。

3 个答案:

答案 0 :(得分:1)

从不FROM子句中使用逗号。 始终使用正确的,明确的,标准 JOIN语法。

您只需要正确的GROUP BY逻辑即可。我想就是这样

SELECT pl.codigo AS Floor_id, count(count distinct h.id) as num_rooms,
       MAX(numero_camas) - count(distinct h.id) AS Free_beds 
FROM habitacion h join
     paciente p
     on p.habitacion_id = h.id   -- just a guess that this is the right join condition
     planta pl
     on h.planta_id = pl.codigo
GROUP BY pl.codigo

答案 1 :(得分:0)

根据戈登·利诺夫(Gordon Linoff)的回答和您的陈述,我想通过这一微小的更改,您应该会得到正确的结果(我想需要对不同的房间进行计数,并且床位数量减去分配的人的总和)上):

SELECT 
     pl.codigo AS Floor_id,  
     count(distinct habitacion_id) as num_rooms, 
     SUM(numero_camas - count(dni)) AS Free_beds 
FROM habitacion h 
join paciente p on p.habitacion_id = h.id 
join condition planta pl on h.planta_id = pl.codigo 
GROUP BY pl.codigo

答案 2 :(得分:0)

您需要两个汇总:每个居住区的床位数,然后是每层可用床位数的总和。一种方法是:

select planta_id, count(*) as rooms, sum(available - occupied) as free_beds
from
(
  select
    planta_id,
    h.id as habitacion_id,
    numero_camas as available,
    (select count(*) from paciente p where p.habitacion_id = h.id) as occupied
  from habitacion h
) habitation_aggregated
group by planta_id
order by planta_id;

您看到我在FROM子句中有一个子查询,它代表一个聚合。这是处理多种聚合的一种非常好的节省方法。