2015-12-13 64 views
1

如何使用下面的代碼得到所有分鐘的總數。我覺得我錯過了一些東西。我將如何得到所有分鐘的最終總和?

結果竟然如下:

ActionLog | Mins 

2015-06-15 16:04:00 | 3 

2015-06-15 16:25:00 | 2 

2015-06-15 16:26:00 | 1 

--create our table 
DECLARE @TableRows TABLE 
(
ID TINYINT, 
ActionLog SMALLDATETIME 
); 

--insert some data 
INSERT INTO @TableRows 
VALUES 
(10,'20150615 16:01:00'), 
(10,'20150615 16:04:00'), 
(10,'20150615 16:23:00'), 
(10,'20150615 16:25:00'), 
(10,'20150615 16:26:00'); 

--set up a CTE which we will perform a self join on 
WITH ExampleCTE 
AS 
(SELECT 
     ROW_NUMBER() OVER(ORDER BY ActionLog) AS RowNum 
    , ActionLog 
FROM @TableRows) 

--now query the CTE using the self join to get our result 
SELECT 
     t1.ActionLog 
    , DATEDIFF(MINUTE,t2.ActionLog,t1.ActionLog) as Mins 
FROM ExampleCTE t1 
    LEFT JOIN ExampleCTE t2 ON T1.RowNum = T2.RowNum + 1 
WHERE 
    DATEDIFF(MINUTE,t2.ActionLog,t1.ActionLog) < 10 
ORDER BY 
    t1.ActionLog 
+1

從各方面分鐘的總和,你僅僅意味着'選擇SUM(DATEDIFF(MINUTE,t2.ActionLog,t1.ActionLog))FROM ...'? – ZLK

+0

該問題詢問總數,查詢返回差異。你想達到什麼目的? –

+0

總差額的總和。 –

回答

1

要找到差異的基礎上查詢的總和:

--now query the CTE using the self join to get our result 
SELECT 
     sum(DATEDIFF(MINUTE,t2.ActionLog,t1.ActionLog)) as Mins 
FROM ExampleCTE t1 
    LEFT JOIN ExampleCTE t2 ON T1.RowNum = T2.RowNum + 1 
WHERE 
    DATEDIFF(MINUTE,t2.ActionLog,t1.ActionLog) < 10 
+0

謝謝 - 我可以發誓我試過了! –

相關問題