2014-10-28 60 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