2013-06-12 64 views
2

在项目中,用户可以预定活动的房间。在一个事件中,我们可以有许多保留(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 - meens比事件已预留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

你能做到在应用程序代码,而不是在SQL变换? –

+0

您是否试过通过将每个事件加入所有房间来选择数据,如果房间已预订或设置了指示符,然后使用PIVOT功能? http://msdn.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx – liebs19

+0

@JoeFrambach报告机制正在使用视图/表值函数来加载数据,所以我尝试更改实际视图。如果我没有找到有趣的解决方案,我将从视图(或视图,如果需要)加载初始数据,并按照您的说法进行转换。谢谢。 – robertw

回答

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

+1

你可能想要添加一个组:) http://sqlfiddle.com/#!2/edcec/ 4/0 – Mr47

+0

这是我第一次使用SQL小提琴...漂亮的小网站应用程序。 – Brian

+0

@briandines我认为这就是我正在寻找的:)当然,我需要分组,每个事件只有一行。谢谢布莱恩!当我在现实生活中查看时,我会通知你:) – robertw