表 1(修订版)
ResvID | ResvDateTime | BufferInd
-----------------------------------------------
1 | 2012-06-11 08:30:00.000 | 1
2 | 2012-06-11 08:30:00.000 | 2
4 | 2013-07-20 12:00:00.000 | 1
5 | 2013-07-20 12:00:00.000 | 2
注意:ResvID(int identity)
,ResvDateTime(datetime)
表 2(缓冲区)
BufferInd | BufferPeriod (minutes)
---------------------------------
1 | 60
2 | 120
注意:BufferInd(int)
,BufferPeriod(int)
我想pivot
在 SQL 视图中将这两个表与下面的两个结果结合起来
ResvID | ResvDateTime | BufferInd1 | BufferInd2
---------------------------------------------------------------------
1 | 2012-06-11 08:30:00.000 | 1 | 2
2 | 2013-07-20 12:00:00.000 | 1 | 2
.
ResvID | ResvDateTime | DateTimeAfterOneHour | DateTimeAfterTwoHour
--------------------------------------------------------------------------------------
1 | 2012-06-11 08:30:00.000 | 2012-06-11 09:30:00.000 | 2012-06-11 10:30:00.000
2 | 2013-07-20 12:00:00.000 | 2013-07-20 13:00:00.000 | 2013-07-20 14:00:00.000
笔记:
日期时间1 =DateAdd(hour, BufferPeriod/60, ResvDateTime)
在哪里BufferInd = 1
日期时间2 =DateAdd(hour, BufferPeriod/60, ResvDateTime)
在哪里BufferInd = 2
这是我在表中声明所有变量的尝试,但失败了。
Create Table Resv
([ResvID] int, [BufferTypeInd] int ,[ResvDT] datetime, [BufferPeriod] int)
;
Insert Into Resv
([ResvID], [BufferTypeInd], [ResvDT], [BufferPeriod])
Values
(1, 1, '2012-06-11 08:30:00.000', 60),
(2, 2, '2012-06-11 08:30:00.000', 180),
(4, 1, '2013-07-20 12:00:00.000', 60),
(5, 2, '2013-07-20 12:00:00.000', 180),
;
我的支点尝试:
SELECT *
FROM
(
(SELECT
[BufferTypeInd], [ResvDT], [BufferPeriod]
FROM Resv)
) AS source
PIVOT
(
MAX([ResvDT])
FOR [BufferTypeInd] IN ([1],[2],[3])
) as pvt;
SELECT ResvID,
MAX(
CASE WHEN
BufferTypeInd = '1'
THEN
DateAdd(hour, BufferPeriod, ResvDT)
ELSE
NULL
END) [1],
MAX(
CASE WHEN
BufferTypeInd = '2'
THEN
DateAdd(hour, BufferPeriod, ResvDT)
ELSE
NULL
END) [2]
FROM Resv
GROUP BY ResvID
请帮助指出我的问题并告诉我应该如何完成枢轴和聚合功能。谢谢。