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

108 views Asked by At
+----+---------+---------+
| 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 |
+----+---------+---------+

I want to select top rooms with count bookings and with count of renewal bookings for each room

To get this result

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

And this live mysql here https://paiza.io/projects/Ao2C6d6pgE133QXQAl03Ug?language=mysql

........

1

There are 1 answers

0
James On BEST ANSWER

Considering your requirement for renewal is not clear, something like this could do the job, using pure 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;