SQL:在两部电影之间找到空格并降低空间

时间:2017-06-04 20:33:17

标签: sql-server sql-server-2016

我正在预订电影院。我必须制定一个对电影有效的时间表。这意味着2部电影之间的时间(空间)应为0。

我需要做的是:我必须制作一个能够在2部电影之间找到30分钟的最大空间并将其设置为0的功能,以便电影具有完美的重叠。

例如:

电影1:11:00-13:00

电影2:13:30-15:00

电影3:15:30-16:00

结果应为:

电影1:11:00-13:00

电影2:13:00-15:00

电影3:15:00-16:00

这是我的表格: ShowTable

1 个答案:

答案 0 :(得分:1)

IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
CREATE TABLE #t(Movie varchar(10),Starttime TIME,EndTime time)
INSERT INTO #t(Movie,Starttime,EndTime)
SELECT 'Movie 1','11:00','13:00' UNION ALL
SELECT 'Movie 2','13:30','15:00' UNION ALL
SELECT 'Movie 3','15:30','16:00'
UPDATE t SET t.Starttime=p.EndTime 
FROM #t AS t
CROSS APPLY(SELECT MAX(tt.EndTime) AS EndTime FROM #t AS tt WHERE DATEDIFF(MINUTE,tt.EndTime,t.Starttime)>0) p
WHERE p.EndTime IS NOT NULL

SELECT * FROM #t
Movie      Starttime        EndTime
---------- ---------------- ----------------
Movie 1    11:00:00.0000000 13:00:00.0000000
Movie 2    13:00:00.0000000 15:00:00.0000000
Movie 3    15:00:00.0000000 16:00:00.0000000

您使用的是哪个版本,如果您使用的是2012+ 你也可以使用LAG

SELECT *,LAG(EndTime)OVER(ORDER BY EndTime) AS NewStartTime FROM #t
Movie      Starttime        EndTime          NewStartTime
---------- ---------------- ---------------- ----------------
Movie 1    11:00:00.0000000 13:00:00.0000000 NULL
Movie 2    13:30:00.0000000 15:00:00.0000000 13:00:00.0000000
Movie 3    15:30:00.0000000 16:00:00.0000000 15:00:00.0000000

我将roomid添加到样本数据中

IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
CREATE TABLE #t(ShowID int,RoomID int, Movie varchar(10),Starttime TIME,EndTime time)
INSERT INTO #t(ShowID,RoomId,Movie,Starttime,EndTime)
SELECT 1,1,'Movie 1','11:00','13:00' UNION ALL
SELECT 3,1,'Movie 2','13:30','15:00' UNION ALL
SELECT 4,1,'Movie 3','15:30','16:00' UNION ALL
SELECT 2,2,'Movie 3','12:30','14:30' UNION ALL
SELECT 5,2,'Movie 1','15:30','16:30' 
SELECT *,LAG(EndTime)OVER(partition by RoomId ORDER BY EndTime) AS NewStartTime FROM #t
UPDATE t SET t.Starttime=isnull(p.NewStartTime,t.Starttime) 
FROM #t AS t
inner join(
  SELECT *,LAG(EndTime)OVER(partition by RoomId ORDER BY EndTime) AS NewStartTime FROM #t   
) as p on t.ShowId=p.ShowId

select *  FROM #t AS t

您想要以下结果吗?


    ShowID  RoomID  Movie   Starttime   EndTime
1   1   1   Movie 1 11:00:00    13:00:00
2   3   1   Movie 2 13:00:00    15:00:00
3   4   1   Movie 3 15:00:00    16:00:00
4   2   2   Movie 3 12:30:00    14:30:00
5   5   2   Movie 1 14:30:00    16:30:00