我有一个预订表,我正在尝试展示预订同一房间的独特客人。
booking_id | check_in_date | check_out_date | guest_id | room_number
------------+---------------+----------------+----------+-------------
1001 | 2018-01-01 | 2018-01-03 | 1 | 702
1002 | 2018-01-01 | 2018-01-05 | 2 | 1104
1003 | 2018-01-05 | 2018-01-07 | 4 | 509
1004 | 2018-01-05 | 2018-01-07 | 4 | 511
1005 | 2018-01-07 | 2018-01-08 | 2 | 404
1006 | 2018-01-07 | 2018-01-09 | 1 | 1104
1007 | 2018-01-10 | 2018-01-12 | 2 | 509
1008 | 2018-01-15 | 2018-01-18 | 6 | 404
1009 | 2018-01-15 | 2018-01-18 | 6 | 406
1010 | 2018-01-15 | 2018-01-17 | 4 | 511
1011 | 2018-01-20 | 2018-01-22 | 2 | 509
1012 | 2018-01-23 | 2018-01-25 | 4 | 511
所以我想要回来:
room_number 404(由唯一的guest_id 2& 6预订的房间)
room_number 509(由唯一的guest_id 2& 4预订的房间)
room_number 1104(由唯一的guest_id 1& 2预订的房间)
我最接近的是这句话:
SELECT room_number, guest_id, COUNT(room_number)
FROM bookings
GROUP BY room_number, guest_id
ORDER BY room_number;
返回:
room_number | guest_id | count
-------------+----------+-------
404 | 2 | 1
404 | 6 | 1
406 | 6 | 1
509 | 4 | 1
509 | 2 | 2
511 | 4 | 3
702 | 1 | 1
1104 | 2 | 1
1104 | 1 | 1
我需要删除出现一次的room_number(room_number 406,511& 702)。
答案 0 :(得分:0)
试试这个。
查询1 :
select a.room_number,a.guest_id, b.count
FROM bookings a JOIN
(
SELECT room_number, count (*) as count
FROM bookings
GROUP BY room_number
HAVING count ( DISTINCT guest_id ) > 1
) b ON a.room_number = b.room_number
ORDER BY room_number
<强> Results 强>:
| room_number | guest_id | count |
|-------------|----------|-------|
| 404 | 6 | 2 |
| 404 | 2 | 2 |
| 509 | 2 | 3 |
| 509 | 4 | 3 |
| 509 | 2 | 3 |
| 1104 | 2 | 2 |
| 1104 | 1 | 2 |
答案 1 :(得分:0)
也许你可以尝试这样的事情。 (此查询适用于SQL SERVER)
SELECT a_tabla.guest_id,COUNT(a_tabla.room_number)
FROM Resultados a_tabla
INNER JOIN (SELECT new_table.guest_id
FROM Resultados new_table
GROUP BY new_table.guest_id
HAVING count(*) > 1) R ON (a_tabla.guest_id = new_table.guest_id)
ORDER BY a_tabla.guest_id
此查询将返回具有1个或更多房间的guest_id,如果您将1更改为2,则将返回具有2个以上房间的guest_id。
我希望这会有所帮助