GROUP BY分组查询的结果

问题描述 投票:2回答:3

使用的表格如下:

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    

我想我有很多问题,因为首先我必须计算每个房间有多少床是免费的(我这样做是通过减去房间里的床数减去分配给那个房间的人数)。

我想知道是否有任何方法可以按照当前查询获得的结果进行分组。

mysql sql database
3个回答
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

0
投票

根据Gordon Linoff和yor声明的答案,我猜这个微小的变化你应该得到正确的结果(我想需要计算不同的房间,并且床的数量减去分配的人需要总结):

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

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子句中有一个代表聚合的子查询。这是处理多个聚合的一种非常好的保存方法。

© www.soinside.com 2019 - 2024. All rights reserved.