MySQL:如何select(计算续订预订数和所有预订数)每个房间?

MySQL: How to select (count renewal bookings & count of all bookings) for each room?

+----+---------+---------+
| id | room_id | user_id |
+----+---------+---------+
|  1 |       5 |      10 |
|  2 |       5 |      20 |
|  3 |       5 |      20 |
|  4 |       6 |      30 |
|  5 |       6 |      40 |
|  6 |       6 |      50 |
|  7 |       7 |      10 |
|  8 |       7 |      10 |
|  9 |       8 |      20 |
| 10 |       9 |      10 |
| 11 |       9 |      10 |
| 12 |       9 |      10 |
+----+---------+---------+

我想 select 对每间客房的预订次数和续订次数进行排名

得到这个结果

+---------+----------------+---------------+
| room_id | total_bookings | total_renewal |
+---------+----------------+---------------+
|       5 |              3 |             1 |
|       6 |              3 |             0 |
|       7 |              2 |             1 |
|       8 |              1 |             0 |
|       9 |              3 |             2 |
|       5 |              1 |             0 |
+---------+----------------+---------------+

这直播 mysql 在这里 https://paiza.io/projects/Ao2C6d6pgE133QXQAl03Ug?language=mysql

.......

考虑到您的续订要求不明确,使用纯 sql:

select 
  s.room_id, 
  sum(s.total_bookings) as total_bookings, 
  sum(case when s.total_bookings > 1 then s.total_bookings - 1 else 0 end) as total_renewal
from (
  select room_id, user_id, count(*) as total_bookings
  from booking
  group by room_id, user_id
  ) s
group by s.room_id;