查询sum,where条件和group by

时间:2016-08-05 08:09:22

标签: mysql sql

我正在尝试对表进行查询 酒店,房型,roomprice, 我正在努力获得罗孚总和作为"总单人房" roomtype = single 按酒店分组 所以我最终得到了酒店和#34; Total Single rooms"

我一直在尝试不同的方式,但我似乎无法让它发挥作用。是的我是SQL lol的新手

由于

2 个答案:

答案 0 :(得分:1)

如果符合您的要求,您应该接受MrVimes解决方案。如果您想要包含酒店连锁总数,您可以使用汇总到该组,例如: -

/*drop table t;
create table t (hotel varchar(3),roomtype varchar(1),price decimal(10,2));
truncate table t;
insert into t values 
('abc','s',10.00),
('abc','s',10.00),
('abc','s',30.00),
('abc','d',10.00),
('def','s',10.00),
('def','s',10.00),
('abc','d',10.00),
('abc','d',10.00),
('abc','d',10.00);
*/

select  case
            when s.hotel is not null then s.hotel
            else 'Total'
            end as hotel,
            s.totalsinglerooms
from
(
select  hotel, sum(price) as totalsinglerooms
from      t
where     roomtype = 's'
group   by hotel with rollup
) s

结果

+-------+------------------+
| hotel | totalsinglerooms |
+-------+------------------+
| abc   |            50.00 |
| def   |            20.00 |
| Total |            70.00 |
+-------+------------------+

答案 1 :(得分:0)

select hotelno,sum(roomprice) as `Total Single Rooms` from room
where roomtype = 'single'
group by hotelno
having sum(roomprice) > 100