快速查询最终用户报告

时间:2013-06-12 16:32:52

标签: sql sql-server tsql

在项目中,用户可以为活动预留房间。在一个事件中,我们可以有许多保留(tblEventTimePeriod)与许多房间(tblEventTimePeriodRoom) 我有像这样的数据库结构。我删除了不必要的列来简化示例,

tblEvent (ID, Name) 
tblEventTimePeriod (ID, EventId)
tblEventTimePeriodRoom (ID, EventTimePeriodId, RoomId)

表之间的关系:

tblEvent to tblEventTimePeriod -> One to many
tblEventTimePeriod to tblEventTimePeriodRoom -> many to many

对于此示例,RoomId可以取值1到5.在实际项目中,它有40个不同的值(其他表中的键),我必须在报告中显示为列。

我的问题是 - 如何构建快速查询以获得如下结果:

EventId | EventName | RoomId_1 | RoomId_2 | RoomId_3 | RoomId_4 | RoomId_5

RoomId_X - 比事件保留了RoomId = X.如果tblEventTimePeriod有这个保留并不重要。

实际解决方案是使用标量UDF(用户定义函数)来获取此信息。一开始很好,但现在执行时间是不可接受的。实际上,对于每一行(tblEvent),它执行子查询,将tblEventTimePeriodRoom连接到tblEventTimePeriod以检查行是否存在。当报告有40列......没有评论:))

我会感激任何暗示!我正在使用SQL Server 2008 R2。

示例数据:

tblEvent:
----------
Id | Name
----------
1 | Event1
2 | Event2
3 | Event3

tblEventTimePeriod:
------------
Id | EventId
------------
12 | 1
13 | 2
14 | 2
15 | 3

tblEventTimePeriodRoom
-------------------------------
Id | EventTimePeriodId | RoomId
-------------------------------
110 | 15 | 1
111 | 15 | 5
112 | 13 | 5
113 | 14 | 2
114 | 14 | 3
115 | 14 | 4
116 | 14 | 5
117 | 12 | 1

Result shoud be:
--------------------------------------------------------------------------
EventId | EventName | RoomId_1 | RoomId_2 | RoomId_3 | RoomId_4 | RoomId_5
--------------------------------------------------------------------------
1 | Event1 | 1 | 0 | 0 | 0 | 0
2 | Event2 | 0 | 1 | 1 | 1 | 1
3 | Event3 | 0 | 0 | 0 | 0 | 1

祝你好运!

1 个答案:

答案 0 :(得分:2)

试试这个:

 /* outer query formats results */
 select EventID, EventName,
 case when RoomID = 1 then 1 else 0 end as Room1,
 case when RoomID = 2 then 1 else 0 end as Room2,
 case when RoomID = 3 then 1 else 0 end as Room3,
 case when RoomID = 4 then 1 else 0 end as Room4,
 case when RoomID = 4 then 1 else 0 end as Room5
 from (
          /* inner query makes the joins */
          select  b.eventid as EventID, a.name as EventName, c.roomid as RoomID
          from _event a inner join _eventTimePeriod b
          on a.id = b.eventid 
          inner join _eventTimePeriodRoom c 
          on c.eventtimeperiod = b.id
) v
order by EventID

我希望这可以帮助你......

SQL Fiddle Example