我有一个如下所示的数据集
CREATE TABLE [dbo].[testTable](
[ID] [int] NULL,
[Type] [varchar](50) NULL,
[Time] [datetime] NULL)
INSERT INTO testTable
(Id,Type,Time)
SELECT '1','Start','Feb 22 2018 6:02AM' UNION ALL
SELECT '1','Move','Feb 22 2018 7:10AM' UNION ALL
SELECT '1','End','Feb 22 2018 7:21AM' UNION ALL
SELECT '1','Idle','Feb 22 2018 7:31AM' UNION ALL
SELECT '1','Idle','Feb 22 2018 7:35AM' UNION ALL
SELECT '1','Start','Feb 22 2018 8:06AM' UNION ALL
SELECT '1','Move','Feb 22 2018 8:25AM' UNION ALL
SELECT '1','Move','Feb 22 2018 8:36AM' UNION ALL
SELECT '1','End','Feb 22 2018 8:48AM' UNION ALL
SELECT '1','Start','Feb 22 2018 10:06AM'
我需要在当天的开始和结束之间获得TOTAL差异。如果Start在夜间持续,则截止时间应为00:00hrs。
实施例: - 它应该是(End-Start)+(End-Start)+(2018-02-23 00.00.00 - Start)。
可以一个接一个地输入2个开始(或结束)
答案 0 :(得分:0)
这有点猜测,因为OP没有指定他们的预期结果。因此,我不知道" EndTime - StartTime
"应该是(也许是几秒钟?我猜到的)。
同样,如果这不对,请发布预期结果并回复我的评论。我们不介意读者。 :)
WITH Leads AS(
SELECT ID,
[Type],
[Time],
ISNULL(LEAD([Time]) OVER (PARTITION BY CONVERT(date, [Time]) ORDER BY [Time]), DATEADD(DAY, 1,CONVERT(date, [Time]))) AS NextTime
FROM testTable
WHERE [Type] in ('Start','End'))
SELECT ID,
SUM(DATEDIFF(SECOND,[Time], NextTime)) AS TotalSeconds
FROM Leads
WHERE [Type] = 'Start'
GROUP BY ID;
编辑:值得注意的是,这也假设 2个开始(或结束)不会一个接一个地输入。样本数据并未表明发生了这种情况,但当然,这并不意味着真实数据是干净的。
答案 1 :(得分:0)
尝试使用此替代解决方案,它不会使用def tell(receiver, message) do
IO.puts "[#{inspect self}] Sending #{message} to #{inspect receiver}"
send receiver, {:ok, self, message}
end
或lead
:
lag
答案 2 :(得分:-1)
您可以在GROUP BY查询中使用LAG()函数,就像任何其他查询一样。唯一的区别是窗口中允许的列(OVER)和LAG中的列是GROUP BY后SELECT中允许的列:
示例表:
CREATE TEMP TABLE foo AS
SELECT date::date, session_id, upload_usage, download_usage,
total_usage_on_a_day
FROM ( VALUES
( '10/21/2014', '0007994b', 37578561 , 6800209 , 44378770 ),
( '10/22/2014', '0007994b', 218113296 , 85272007 , 303385303 ),
( '10/23/2014', '0007994b', 552228616 , 252390680 , 804619296 ) ,
( '10/24/2014', '0007994b', 799772020 , 391196041 , 1190968061 ),
( '10/25/2014', '0007994b', 1047233978 , 529908804 , 1577142782 ),
( '10/26/2014', '0007994b', 1294608258 , 668515778 , 1963124036 ),
( '10/27/2014', '0007994b', 1066656794 , 557318645 , 2573613674 ),
( '10/27/2014', '00079e4e', 12949219 , 7265243 , 20214462 ),
( '10/28/2014', '00079e4e', 203871297 , 114308478 , 318179775 ),
( '10/29/2014', '00079e4e', 445466682 , 251486943 , 696953625 ),
( '10/30/2014', '00079e4e', 183499477 , 109643736 , 893143213 )
) AS t( date, session_id, upload_usage, download_usage, total_usage_on_a_day
);
示例查询:
select
date,
session_id,
sum(upload_usage) as upload,
sum(download_usage) as download,
sum(total_usage_on_a_day) as total_as_cumm,
sum(total_usage_on_a_day)
- coalesce(lag(sum(total_usage_on_a_day)) over (partition by session_id
order by date), 0)
as expected_difference
from jiodba.s_crc_zda_mon_conn_usage
where gpart = '1100043958'
and zzaccess_ntwk_id = 'FTTH'
group by session_id, date
order by session_id, date
limit 100 ;