[英]SQL Server 2012 window function
I have the following table which holds status of jobs in a history table. 我有下表,其中包含历史表中的作业状态。
jobOrderId | dateAdded | Status
-----------|-------------------------|-------
4909 | 2015-08-26 18:15:07.527 | OPEN
4909 | 2015-08-28 13:35:38.997 | CLOSE
4909 | 2015-08-31 12:16:29.787 | OPEN
4910 | 2015-08-27 12:16:42.72 | OPEN
4910 | 2015-08-28 17:04:43.617 | CLOSE
4910 | 2015-08-31 17:01:27.337 | OPEN
4911 | 2015-08-27 16:08:39.467 | OPEN
I would like to get the following output 我想获得以下输出
jobOrderId | opendate | closedate
-----------|------------|-----------
4909 | 2015-08-26 | 2015-08-28
4909 | 2015-08-31 | NULL
4910 | 2015-08-27 | 2015-08-28
4910 | 2015-08-31 | NULL
4911 | 2015-08-27 | NULL
Can any one suggest me how to get this kind of output using SQL Server 2012 window functions? 任何人都可以建议我如何使用SQL Server 2012窗口函数获得这种输出?
SELECT t.jobOrderId
, CONVERT(DATE,dateAdded) [OpenDate]
,(SELECT TOP 1 CONVERT(DATE,dateAdded)
FROM TableName
WHERE jobOrderId = t.jobOrderId
AND dateAdded > t.dateAdded
AND [Status] = 'CLOSE'
ORDER BY dateAdded ASC) AS [CloseDate]
FROM TableName t
WHERE t.[Status] = 'OPEN'
SELECT t.jobOrderId
, CONVERT(DATE,dateAdded) [OpenDate]
,C.CloseDate
FROM TableName t
OUTER APPLY ( SELECT TOP 1 CONVERT(DATE,dateAdded)
FROM TableName
WHERE jobOrderId = t.jobOrderId
AND dateAdded > t.dateAdded
AND [Status] = 'CLOSE'
ORDER BY dateAdded ASC) c ([CloseDate])
WHERE t.[Status] = 'OPEN'
Here is a working example. 这是一个有效的例子。
NOTE i have not forgotten to add a where for closed, in my function. 注意我没有忘记在我的功能中添加一个关闭的位置。 Its simply not needed as based on the rules Ie OPEN -> CLOSED you would always find a closed after an open or nothing at all.
它根本不需要根据规则即开放 - >关闭你总是会在开放后发现关闭或者根本没有关闭。 So you don't need to check for the status.
所以你不需要检查状态。 If there was a second open after the open then you could change the code or correct your data.
如果在打开后第二次打开,则可以更改代码或更正数据。
DECLARE @Data TABLE(jobOrderId INT,dateAdded DATETIME,Status NVARCHAR(8))
INSERT INTO @Data
VALUES
(4909,'2015-08-26 18:15:07.527','OPEN'),
(4909,'2015-08-28 13:35:38.997','CLOSE'),
(4909,'2015-08-31 12:16:29.787','OPEN'),
(4910,'2015-08-27 12:16:42.72','OPEN'),
(4910,'2015-08-28 17:04:43.617','CLOSE'),
(4910,'2015-08-31 17:01:27.337','OPEN'),
(4911,'2015-08-27 16:08:39.467','OPEN')
SELECT jobOrderId,CAST(dateAdded AS DATE),(SELECT CAST(MIN(dateAdded) AS DATE) FROM @Data AS DB WHERE DA.dateAdded < DB.dateAdded AND DA.jobOrderId = DB.jobOrderId)
FROM @Data AS DA
WHERE Status = 'OPEN'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.