酒店名称和月份的预订总数

时间:2016-06-17 15:30:49

标签: sql sql-server count

我试图想出一个SQL Server脚本,该脚本按酒店名称和(签入)月份显示预订总数。任何帮助将不胜感激。

这是我正在寻找的输出类型:

HotelName          Month     TotalReservations
==============================================
Algonquin Hotel    June      300
Algonquin Hotel    July      275
Algonquin Hotel    August    295
The Four Seasons   June      485 
The Four Seasons   July      445
The Ritz-Carlton   June      ...

这里有一些相关的表信息:

HOTEL:

HotelID(PK), HotelName, HotelAddress, HotelCity, HotelState, HotelPostalCode

预订:

ReservationID(PK), GuestID, RoomID(FK), CheckinDate, NumberofNights

ROOM(仅用于表连接):

RoomID(PK), HotelID(FK)

3 个答案:

答案 0 :(得分:0)

您可以加入表格,使用datename功能获取月份名称,按酒店名称和月份分组并应用count

SELECT   h.hotelname, DATENAME('m', checkindate), COUNT(*)
FROM     hotel h
JOIN     room  r ON h.hotelid = r.hotelid
JOIN     reservation rs ON s.roomid = rs.roomid
GROUP BY h.hotelname, DATENAME('m', checkindate)

答案 1 :(得分:0)

试试这个:

select h.hotelname , 
    DATENAME(MONTH, re.checkindate) as Month, 
    count(*) as TotalReservations
from room as r 
    inner join hotel as h on r.hotelid = h.hotelid
    inner join reservation as re on r.roomid  = re.roomid
group by h.hotelname, 
    DATENAME(MONTH, re.checkindate)

如果您有多年,请在查询的selectgroup by条款中替换此行

CONCAT(DATENAME(MONTH, re.checkindate), ' ',  DATENAME(YEAR, re.checkindate))

答案 2 :(得分:0)

select 
    h.hotelname, 
    datename(month,res.checkindate) as month , 
    count(*) reservations 
from Hotel h 
join room rm 
    on h.hotelid=rm.hotelid
join RESERVATION res 
    on res.roomid=rm.roomid
group by h.hotelname, datename(month,res.checkindate )