0

我需要一个查询,给我带来一个像

7 AM | 7:30 AM | 8 AM   | 8:30 AM...........|6:30 PM|
----- --------- -------- ----- ............. -------
     | Booked  | Booked | Booked ...........|       |

我的表名是:zUSM_RoomReservationInfo 这是表的结构和数据

ReservationID RoomId  StartDateTime           EndDateTime             
------------- ------- ----------------------- ----------------------- 
1             102     2013-02-01 10:00:00.000 2013-02-01 12:00:00.000 
2             201     2013-01-27 16:00:00.000 2013-01-27 17:00:00.000 
3             102     2013-02-01 14:00:00.000 2013-02-01 16:00:00.000   

通过提供一个日期和房间 ID 作为输入,它应该给我上面提到的表格。

4

1 回答 1

1

请试试:

DECLARE @RoomID NVARCHAR(10), @DtParam NVARCHAR(20), @dt1 DATETIME, @dt2 DATETIME, @Col NVARCHAR(MAX), @Query NVARCHAR(MAX)
select @RoomID='102', @DtParam='01-Feb-2013', @dt1='07:00', @dt2='17:00', @Col='', @Query=''

CREATE TABLE #table (DT DATETIME)

while @dt1<=@dt2
begin
    SET @Col=@Col+'['+CONVERT(CHAR(5), @dt1, 108)+'],'
    insert into #table values (@dt1)
    SET @dt1=dateadd(minute, 30, @dt1)
end

select @Col=LEFT(@Col, LEN(@Col) -1)

set @Query='select '+@Col+' From(
select DT, ReservationID From #table t1 left outer join (select * from zUSM_RoomReservationInfo
where RoomID='+@RoomID+' AND DATEADD(dd, 0, DATEDIFF(dd, 0, StartDateTime))=CONVERT(DATETIME, '''+@DtParam+'''))t2 on t1.DT
between CONVERT(CHAR(5), StartDateTime, 108) and CONVERT(CHAR(5), EndDateTime, 108)

)x pivot (count(ReservationID) for DT IN ('+  @Col+'))PIV'
exec (@Query)

drop table #table
于 2013-02-04T12:16:24.260 回答