答案 0 :(得分:0)
如果您使用的是SQL Server 2012或更高版本,那么LEAD()分析函数可以非常简单地生成您想要的结果:
SELECT employeeNo, stations_id, itemno, datetime AS [Start Shirt],
LEAD(datetime) OVER (ORDER BY datetime) AS [End Shift]
FROM yourTable
如果运行上面的内容会导致内置函数错误,您可以尝试通过以下方式更改数据库的兼容级别:
ALTER DATABASE yourDBName
SET COMPATIBILITY_LEVEL = 110
答案 1 :(得分:0)
尝试以下查询,它会为您提供确切的所需输出:
DECLARE @EMPLOYEE TABLE(ID INT,EMPLOYEENO VARCHAR(100),STATIONS_ID INT,ITEMNO INT,DATETIME1 DATETIME)
INSERT INTO @EMPLOYEE VALUES
(30179,'E13784',38,70077780,'3/25/2017 22:59'),
(30177,'E13784',38,70077780,'3/26/2017 22:59'),
(30173,'E13784',38,70077780,'3/27/2017 22:58')
SELECT EMPLOYEENO,STATIONS_ID,ITEMNO,DATETIME1 START_SHIFT,
(
SELECT DATETIME1 FROM (SELECT ROW_NUMBER() OVER(ORDER BY ID DESC)SNO,* FROM @EMPLOYEE)T2
WHERE T1.SNO=T2.SNO-1
)END_SHIFT
FROM
(SELECT ROW_NUMBER() OVER(ORDER BY ID DESC)SNO,* FROM @EMPLOYEE) T1
输出
-----------------------------------------------------------------------------
--EMPLOYEENO STATIONS_ID ITEMNO START_SHIFT END_SHIFT
-----------------------------------------------------------------------------
E13784 38 70077780 2017-03-25 22:59:00.000 2017-03-26 22:59:00.000
E13784 38 70077780 2017-03-26 22:59:00.000 2017-03-27 22:58:00.000
E13784 38 70077780 2017-03-27 22:58:00.000 NULL
-----------------------------------------------------------------------------