使用SQL汇总并找到客户最常用的房间

时间:2018-11-13 11:57:37

标签: sql tsql

我正在尝试查找所有按客户分组的预订,并且仅显示他们使用最多的房间(以及预订的数量)。

这是我到目前为止的查询,但是问题是它将显示他们的所有预订和数量,我只对预订最多的房间感兴趣,我不确定要使用什么最佳功能来实现这个。我以为先通过CREATE TABLE rooms ( room_id int NOT NULL AUTO_INCREMENT PRIMARY KEY, room_name varchar(50) ); CREATE TABLE bookings ( id int NOT NULL AUTO_INCREMENT PRIMARY KEY, account_id int, room_id int ); 表进行查询,然后再进行子查询以获取预订号,但是我觉得这可能效率较低(特别是因为我们有大约1000万个帐户记录)。

模式:

INSERT INTO rooms (room_id, room_name)
VALUES ('1', 'Suite A'), 
('2', 'Suite B'),
('3', 'Suite C'),
('4', 'Suite D'),
('5', 'Suite X');

INSERT INTO bookings (account_id, room_id)
VALUES ('123', '1'), 
('123', '1'),
('123', '1'),
('123', '1'),
('123', '1'),
('123', '2'),
('123', '3'),
('123', '4'),
('123', '4'),
('123', '5'),
('123', '1'),
('124', '4'),
('124', '5'),
('124', '1');

样本数据:

select account_id, count(room_id), room_id
from bookings
group by account_id, room_id

查询:

account_id | most booked room | count
123        | Room A           | 2
124        | Room B           | 30

SQL Fiddle Link

所需的输出:

{{1}}

2 个答案:

答案 0 :(得分:0)

您希望每个帐户拥有最普通的房间。从统计上讲,这称为 mode

您可以使用窗口函数来计算它:

select ar.*
from (select account_id, room_id, count(*) as cnt, 
             row_number() over (partition by account_id order by count(*) desc) as seqnum
      from bookings
      group by account_id, room_id
     ) ar
where seqnum = 1;

Here是dbfiddle,使用MySQL 8,因此语法与SQL Server更加兼容。

答案 1 :(得分:0)

您可以使用相关子查询

DEMO

select * from
(select account_id, count(room_id) as cnt, room_id
from bookings
group by account_id, room_id
)A inner join rooms on A.room_id=rooms.room_id
where cnt in (select max(cnt) from
                (select account_id, count(room_id) as cnt, room_id
from bookings
group by account_id, room_id
)B where A.account_id=B.account_id)