2014-10-28 62 views
0

我希望此查询可以与我的表一起使用,而不仅仅是示例数据。SQL查询更改

Declare @Date char(8) = '20141013' 
; 
WITH cte as 
(
    SELECT * 
    FROM -- use your table name instead of the VALUES construct 
    (VALUES 
    ('09:00:00','12:30:00' ,'7-3', '20140919'), 
    ('15:00:00','17:00:00' ,'7-2', '20141013'), 
    ('14:00:00','16:00:00' ,'7-3', '20140919')) x(EventStart , EventEnd,Rooms, DayStarts) 
), cte_Days_Rooms AS 
-- get a cartesian product for the day specified and all rooms as well as the start and end time  to compare against 
(
    SELECT y.EventStart,y.EventEnd, x.rooms,a.DayStarts FROM 
    (SELECT @Date DayStarts) a 
    CROSS JOIN 
    (SELECT DISTINCT Rooms FROM cte)x 
    CROSS JOIN 
    (SELECT '09:00:00' EventStart,'09:00:00' EventEnd UNION ALL 
    SELECT '22:00:00' EventStart,'22:00:00' EventEnd) y   
), cte_1 AS 
-- Merge the original data an the "base data" 
(
    SELECT * FROM cte WHERE [email protected] 
    UNION ALL 
    SELECT * FROM cte_Days_Rooms 
), cte_2 as 
-- use the ROW_NUMBER() approach to sort the data 
(
    SELECT *, ROW_NUMBER() OVER(PARTITION BY DayStarts, Rooms ORDER BY EventStart) as pos 
    FROM cte_1 
) 
-- final query: self join with an offest of one row, eliminating duplicate rows if a room is booked starting 9:00 or ending 22:00 
SELECT c2a.DayStarts, c2a.Rooms , c2a.EventEnd, c2b.EventStart 
FROM cte_2 c2a 
INNER JOIN cte_2 c2b on c2a.DayStarts = c2b.DayStarts AND c2a.Rooms =c2b.Rooms AND c2a.pos = c2b.pos -1 
WHERE c2a.EventEnd <> c2b.EventStart 
ORDER BY c2a.DayStarts, c2a.Rooms 

我的表称为Events这是我的数据库是什么样子:

Event  EventStart EventEnd Days    Rooms DayStarts 
CISC 3660 09:00:00 12:30:00 Monday    7-3  9/19/2014 
MATH 2501 15:00:00 17:00:00 Monday:Wednesday 7-2  10/13/2014 
CISC 1110 14:00:00 16:00:00 Monday    7-3  9/19/2014 

此查询工作正常,并做什么它应该与被查询中创建的数据。在查询的第6行,它说use your table name instead of the values construct当我做from [events]它给出了一个错误,说Invalid object name 'Events'.所以问题是我将如何使查询从我的表中获取值。

回答

0

根据错误消息,您可能需要将[模式名称] .Events。如果您登录的用户的默认架构不是Events所属模式,那么它将不知道您所指的是哪个表。希望这可以帮助。

+0

我该如何找出模式名称?我只注意到一个简单的声明也不起作用:'select * from events'。 – User765876 2014-10-28 14:56:16

+0

好的,我得到了那个工作。我刚打开一个新的查询页面,它工作正常。但是在第19和20行中,我将它们替换为什么? – User765876 2014-10-28 15:24:47

+0

对于第19行和第20行,你能更具体一些吗?并且替换“他们”? – Maxqueue 2014-10-28 15:47:01