Sql查询前一行优化 [英] Sql Query Pervious Row Optimisation
本文介绍了Sql查询前一行优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的表结构
MyTable
-----------
ObjectID int (Identity), -- Primary Key
FileName varchar(10),
CreatedDate datetime
...........
...........
...........
我需要获取在文件中创建记录所花费的时间......即......同一文件中的前一条记录与同一文件的当前记录之间经过的时间
I need to get the time taken to create record in a file... ie... Time elapsed between the previous record in the same file and the current record of the same file
即...如果记录是
ObjectID FileName CreatedDate (just showing the time part here)
-------- -------- -----------
1 ABC 10:23
2 ABC 10:25
3 DEF 10:26
4 ABC 10:30
5 DEF 10:31
6 DEF 10:35
所需的输出是...
ObjectID FileName CreatedDate PrevRowCreatedDate
-------- -------- ----------- ---------------
1 ABC 10:23 NULL
2 ABC 10:25 10:23
3 DEF 10:26 NULL
4 ABC 10:30 10:25
5 DEF 10:31 10:26
6 DEF 10:35 10:31
到目前为止,我收到了这个查询,但比预期的要花费很长时间......有没有更好的方法来做到这一点......
So far I got this query, but it is taking a very long time than expected... Is there a better way to do it...
Select A.ObjectID,
A.FileName
A.CreatedDate as CreatedDate,
B.PrevRowCreatedDate,
datediff("SS", '1900-01-01 00:00:00', Coalesce((A.CreatedDate - B.PrevRowCreatedDate),0)) as secondsTaken
from MyTable as A
Cross Apply (
(Select PrevRowCreatedDate = Max(CreatedDate) from MyTable as BB
where BB.FileName = A.FileName and
BB.CreatedDate < A.CreatedDate
)
) as B
如果您需要更多信息,请告诉我
Please let me know incase you need more information
谢谢
推荐答案
SELECT t1.FileName, t1.CreatedDate, t2.CreatedDate as PrevCreatedDate
FROM
(SELECT FileName, CreateDate,
ROW_NUMBER() OVER(PARTITION BY FileName ORDER BY CreatedDate) AS OrderNo
FROM MyTable) t1
LEFT JOIN
(SELECT FileName, CreateDate,
ROW_NUMBER() OVER(PARTITION BY FileName ORDER BY CreatedDate) AS OrderNo
FROM MyTable) t2
ON (t1.FileName = t2.FileName AND t1.OrderNo = t2.OrderNo - 1)
或者最好使用WITH",因为查询是相同的:
Or may be better use 'WITH', because queries is identical:
WITH t(ObjectID, FileName, CreatedDate, OrderNo) AS
(SELECT ObjectID, FileName, CreatedDate,
ROW_NUMBER() OVER(PARTITION BY FileName ORDER BY CreatedDate) AS OrderNo
FROM MyTable)
SELECT t1.ObjectID, t1.FileName, t1.CreatedDate, t2.CreatedDate AS PrevCreatedDate,
DATEDIFF("SS", '1900-01-01 00:00:00',
COALESCE((t1.CreatedDate - t2.CreatedDate),0)) AS secondsTaken
FROM t t1 LEFT JOIN t t2
ON (t1.FileName = t2.FileName AND t1.OrderNo = t2.OrderNo + 1)
这篇关于Sql查询前一行优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文