我目前有一个数据库表,记录的工作,有8个可用的时隙预订
+-----------+
|tbl_booking|
+-----------+
|room_id |
|date |
|timeslot |
|booking |
+-----------+
sample data
+-----------+----------+-----------+
|room_id | date | timeslot |
+-----------+----------+-----------+
|1 |2018-01-01| 1 |
|1 |2018-01-01| 2 |
|1 |2018-01-01| 4 |
|2 |2018-01-01| 1 |
+-----------+----------+-----------+
intended outcome - when statement filters for bookings on 2018-01-01
+-----------+----------+-----------+----------+-----------+
|room |timeslot1 | timeslot2 |timeslot3 | timeslot4 |
+-----------+----------+-----------+----------+-----------+
|1 | X | X | | X |
|2 | X | | | |
+-----------+----------+-----------+----------+-----------+
我从这句话开始:
SELECT * from tbl_booking WHERE date = '2018-01-01' GROUP BY room_id
这将返回结果以查看按房间分组的结果。我想知道我应该去哪里,从这里也有结果显示,它的时隙,显示在一个表格显示预订状态,每间客房的时隙在一天?
我应该使用sql语句,还是完全走错了方向?
任何帮助都将不胜感激。谢谢您!
2条答案
按热度按时间nxowjjhe1#
如果您正在寻找动态解决方案,那么您必须使用透视表。
选择from(selectfrom yourtable)作为可诱惑的枢轴(count(room)for timeslot in(timeslot列表))作为tempslot
有关更多信息,请查看此链接mysql pivot表
nbewdwxp2#
您想对数据执行的操作并不好,如果您有固定数量的时隙,则可以对列进行如下硬编码:
(请参阅sql fiddle)
你可以用
MAX
如果你只是想看看是否至少有一个预订存在sql要包含备注,可以通过一个组来欺骗它选择备注
MAX
```SELECT room_id,
SUM(CASE WHEN timeslot = 1 then 1 else 0 END) AS Timeslot1,
MAX(CASE WHEN timeslot = 1 THEN remark ELSE '' END) AS Timeslot1Remark,
SUM(CASE WHEN timeslot = 2 then 1 else 0 END) AS Timeslot2,
MAX(CASE WHEN timeslot = 2 THEN remark ELSE '' END) AS Timeslot2Remark,
SUM(CASE WHEN timeslot = 3 then 1 else 0 END) AS Timeslot3,
MAX(CASE WHEN timeslot = 3 THEN remark ELSE '' END) AS Timeslot3Remark,
SUM(CASE WHEN timeslot = 4 then 1 else 0 END) AS Timeslot4,
MAX(CASE WHEN timeslot = 4 THEN remark ELSE '' END) AS Timeslot4Remark
FROM tbl_booking
GROUP BY room_id