如何计算每种类型的房间和总房间的数量?

时间:2015-11-05 14:04:32

标签: php sql codeigniter

我的查询是这样的:

SELECT name, room_type, room_number FROM table_room

结果是这样的: enter image description here

我想添加一个这样的描述:

Single Room : 3 Room
Double Room : 2 Room
Family Room : 1 Room
Total  : 6 room

其他信息:

Single Room 1 : Tony
Single Room 2 : Eden
Single Room 3 : Christiano
Double Room 1 : Wayne and Christina
Double Room 2 : Ryan and Jose
Family Room 1 : David, Peter and Carlo

总计:6个房间,而不是10个房间

我试过了。但我仍然很难。

谢谢。

要确定房间数,不是基于房型,而是房间号

所以根据上面的表格会产生这样的结果:

Single Room : 3 Room
Double Room : 2 Room
Family Room : 1 Room
Total  : 6 room

其他信息:

Single Room 1 : Tony
Single Room 2 : Eden
Single Room 3 : Christiano
Double Room 1 : Wayne and Christina
Double Room 2 : Ryan and Jose
Family Room 1 : David, Peter and Carlo

总计:6个房间,而不是10个房间

很抱歉,如果我的问题不太清楚

非常感谢

5 个答案:

答案 0 :(得分:2)

您可以通过以下方式获得所需的结果:

select room_type, count(*) as roomcount from test group by room_type
union all
select 'Total', count(*) as roomcount from test

结果:

+-------------+----------+
| room_type   | count(*) |
+-------------+----------+
| Double Room |        4 |
| Family Room |        3 |
| Single Room |        3 |
| Total       |       10 |
+-------------+----------+

您可以使用PHP检索此结果并根据自己的喜好对其进行格式化。

如果你使用MySQL,你甚至可以做这样的事情来直接从数据库获取格式化输出,如下所示:

select concat(
  room_type, ' : ', roomcount,
  case when roomcount < 2 then ' Room' else ' Rooms' end
) as outputstring
from (
select room_type, count(*) as roomcount from test group by room_type
union all
select 'Total', count(*) as roomcount from test
) sub_query

结果:

+-----------------------+
| outputstring          |
+-----------------------+
| Double Room : 4 Rooms |
| Family Room : 3 Rooms |
| Single Room : 3 Rooms |
| Total : 10 Rooms      |
+-----------------------+

答案 1 :(得分:0)

使用countgroup by

SELECT count(*) as total,room_type FROM table_room group by 
room_type

总房间数: -

 SELECT count(*) as total_room FROM table_room 

在单一查询中: -

SELECT count(*) as total,room_type,
(SELECT count(*) FROM table_room) as total_room FROM table_room group by 
room_type

答案 2 :(得分:0)

取决于您的rdbms,您可以在返回之前构造字符串

我添加了一列order_id,因此我可以订购并在最后一行显示total

SELECT * 
FROM (
  SELECT 1 order_id, room_type + ': ' +  Count(*) + ' Room' as desc
  FROM table_room
  GROUP BY room_type
  UNION ALL
  SELECT 2 order_id, 'Total : ' +  Count(*) + ' Room' as desc
  FROM table_room
)
ORDER BY order_id

注意:除非您加入ORDER BY

,否则无法保证结果订单

注2:最好的方法是让您的查询仅返回群组总数

| Double Room |        4 |
| Family Room |        3 |
| Single Room |        3 |

并计算php UI中的总数。这样,您的查询只有一种类型的数据,而不必担心订单

答案 3 :(得分:0)

select room_type, count(*) as roomcount from test group by room_type
UNION
select 'Total' as room_type , count(*) as roomcount from test

希望这有帮助。

答案 4 :(得分:0)

SQL Fiddle

SELECT room_type, COUNT(*) AS total
FROM table_room
GROUP BY room_type
UNION ALL
SELECT 'Total' AS room_type, COUNT(*) AS total
FROM table_room;