简体   繁体   中英

How to group each count value of different condition in the same table into 1 table

i have 1 Inner join table

SELECT COUNT(*) as dirtyRoom FROM t_room INNER JOIN t_room_type ON t_room.roomType = t_room_type.code WHERE status = 'sPVDirty'   output :  dirtyRoom : 13


SELECT COUNT(*) as readyRoom FROM t_room INNER JOIN t_room_type ON t_room.roomType = t_room_type.code WHERE status = 'sPVReady'   output : readyRoom : 33

SELECT COUNT(*) as maintenanceRoom FROM t_room INNER JOIN t_room_type ON t_room.roomType = t_room_type.code WHERE status = 'sPVMaint' output : maintenanceRoom : 4

I WANT to group each count value of different condition into 1 table with 3 column that display each each value

output : Table1

 dirtyRoom             readyRoom           maintenanceRoom
    13                     33                     4   

how to do that?

Try this

SELECT COUNT(IF(status='sPVDirty',status,0)) As DirtyRoom,
       COUNT(IF(status='sPVReady',status,0)) As ReadyRoom,
       COUNT(IF(status='sPVMaint',status,0)) As MaintenanceRoom 
FROM t_room INNER JOIN t_room_type ON t_room.roomType = t_room_type.code

Or:

SELECT SUM(IF(status='sPVDirty',1,0)) As DirtyRoom,
       SUM(IF(status='sPVReady',1,0)) As ReadyRoom,
       SUM(IF(status='sPVMaint',1,0)) As MaintenanceRoom 
FROM t_room INNER JOIN t_room_type ON t_room.roomType = t_room_type.code

So your Output Will Be

+------------+------------+--------------------+
| DirtyRoom  | ReadyRoom  |MaintenanceRoom     |
+------------+------------+--------------------+
| 13         | 33         |4                   |
+------------+------------+--------------------+

Try

SELECT 
    IF(status = 'sPVDirty', count(status), 0) as dirtyRoom,
    IF(status = 'sPVReady', count(status), 0) as readyRoom,
    IF(status = 'sPVMaint', count(status), 0) as maintenanceRoom,
FROM t_room INNER JOIN t_room_type ON t_room.roomType = t_room_type.code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM