鉴于这两个表:
tblHotels:
id INT
hotel_name VARCHAR
booking_open_date DATETIME
booking_close_date DATETIME
tblRegistrantHotelDates:
id INT
registrant_id INT
hotel_id INT
booking_date DATETIME
... tblRegistrantHotelDates 中的每个条目代表一个住在酒店一晚的注册人(因此,入住两晚的注册人将在表中有两行,具有相同的酒店ID和不同的booking_date)......
如何以这种格式获得一组结果:
registrant_id,hotel_id,3rd March,4th March,5th March
42,6,1,0,1
57,6,1,1,0
...通过从* tblHotels.booking_open_date *循环到* tblHotels.booking_close_date来生成列名称*(我对列名的确切日期格式不感到烦恼),每个中都有1/0日期列表示注册人是否将在该日期入住该酒店?
注意:并非所有酒店都有相同的预订开放/关闭日期,尽管它们将始终重叠。因此,生成的列名称必须从最早的酒店的开放日期到最新酒店的截止日期。
这在SQL中是否可行?
编辑 - 这就是我所拥有的。它不会将日期作为列名,它只能用于我明确查询的日期,这是一个令人震惊的笨拙和缓慢的混乱。对于寻找类似解决方案的任何其他人:这是不怎么做的。希望知道该做什么的人很快就会出现:SELECT
reg.first_name,
reg.last_name,
MIN(h.booking_open_date) AS day_1,
(
SELECT 1 FROM tblRegistrantHotelDates rh
WHERE rh.hotel_id = h.id
AND rh.registrant_id = reg.id
AND rh.hotel_date = MIN(h.booking_open_date)
) AS day_1_booked,
CASE WHEN DATE_ADD(MIN(h.booking_open_date),INTERVAL 1 DAY) < MAX(h.booking_close_date) THEN
DATE_ADD(MIN(h.booking_open_date),INTERVAL 1 DAY)
END AS day_2,
(
SELECT 1 FROM tblRegistrantHotelDates rh
WHERE rh.hotel_id = h.id
AND rh.registrant_id = reg.id
AND rh.hotel_date = DATE_ADD(MIN(h.booking_open_date),INTERVAL 1 DAY)
) AS day_2_booked,
CASE WHEN DATE_ADD(MIN(h.booking_open_date),INTERVAL 2 DAY) < MAX(h.booking_close_date) THEN
DATE_ADD(MIN(h.booking_open_date),INTERVAL 2 DAY)
END AS day_3,
(
SELECT 1 FROM tblRegistrantHotelDates rh
WHERE rh.hotel_id = h.id
AND rh.registrant_id = reg.id
AND rh.hotel_date = DATE_ADD(MIN(h.booking_open_date),INTERVAL 2 DAY)
) AS day_3_booked,
## etc etc...
MAX(h.booking_close_date) AS day4,
(
SELECT 1 FROM tblRegistrantHotelDates rh
WHERE rh.hotel_id = h.id
AND rh.registrant_id = reg.id
AND rh.hotel_date = MAX(h.booking_close_date)
) AS day_4_booked
FROM tblRegistrants reg
LEFT JOIN tblRegistrantHotelDates hd ON hd.registrant_id = reg.id
LEFT JOIN tblHotels h ON hd.hotel_id = h.id
GROUP BY reg.id