我有一张ITEM , OPCODE ,WorkCenter, LOT , COIL ,Strt_Time(DateTime)
的表。我想返回Previous WorkCenter和NextWorkCenter以及ITEM , OPCODE ,WorkCenter, LOT , COIL ,Strt_Time
。
一个特殊的LOT线圈将从工作中心路由到工作中心,并带有时间戳(Strt_time
)
请在SQL Server 2008中建议如何实现这一目标。
提前致谢。
答案 0 :(得分:0)
在SQL Server 2012中,您应该使用LEAD
和LAG
函数。
由于您使用的是SQL Server 2008,因此这是一种解决方法:
WITH WorkCenter_details AS
(
SELECT
ROW_NUMBER() OVER ( ORDER BY Strt_Time) rn,
(ROW_NUMBER() OVER ( ORDER BY Strt_Time)) / 2 rndiv2,
(ROW_NUMBER() OVER ( ORDER BY Strt_Time) + 1) / 2 rnplus1div2,
ITEM, OPCODE, WorkCenter, LOT, COIL, Strt_Time
FROM
MyTable
)
SELECT
rn, rndiv2, rnplus1div2,
ITEM, OPCODE, WorkCenter, LOT, COIL, Strt_Time,
CASE
WHEN rn % 2 = 1
THEN MAX(CASE WHEN rn % 2 = 0 THEN WorkCenter END) OVER (PARTITION BY rndiv2)
ELSE MAX(CASE WHEN rn % 2 = 1 THEN WorkCenter END) OVER (PARTITION BY rnplus1div2)
END AS WorkCenter_Previous,
CASE
WHEN rn % 2 = 1
THEN MAX(CASE WHEN rn % 2 = 0 THEN WorkCenter END) OVER (PARTITION BY rnplus1div2)
ELSE MAX(CASE WHEN rn % 2 = 1 THEN WorkCenter END) OVER (PARTITION BY rndiv2)
END AS WorkCenter_Next
FROM
WorkCenter_details
ORDER BY
ITEM, Strt_Time
仅当工作中心为数字
时才有效