Type Status date ID Users
-------------------------------------------------------------
2 1 6/1/2015 8:43:13.557 AM 1140914474 2B 4E
1 1 6/1/2015 8:43:40.057 AM 1140914474 2B 4E
2 1 6/1/2015 12:29:15.093 PM 655666666 2B 4E
1 1 6/1/2015 12:32:43.067 PM 655666666 2B 4E
2 1 6/1/2015 6:02:30.557 PM 1694543676 2B 4E
1 1 6/1/2015 6:14:34.180 PM 1694543676 2B 4E
我需要在行类型2和类型1之间获取日期差异,并将所有时间总计为天。
答案 0 :(得分:0)
与SQL Server 2005相同:-)此查询将返回您要聚合的所有数据
select
cast(b.date as date) day,
datediff(s, a.date, b.date) diff
from
mytable a
join
mytable b on a.ID = b.ID
where
a.Type = 2 and b.Type = 1
将此查询用作CTE:
with result as
(
select
cast(b.date as date) dt,
datediff(s, a.date, b.date) diff
from
mytable a
join
mytable b on a.ID = b.ID
where
a.Type = 2 and b.Type = 1
)
select
dt, sum(diff) difftotal
from
result
group by
dt;
答案 1 :(得分:0)
您的问题的查询将如下:
select
datea,
sum(differenceSec) as Total
from (
select a.type,
cast(a.date as date) datea,
cast(b.date as date) dateb,
DATEDIFF ( ss , a.date , b.date ) as differenceSec
from data a
inner join data b
on b.id = a.id
and b.type = 1
where a.type = 2 ) result
group by datea
查询的第一部分,按日分组结果并求它们。在子查询中,我们获得了类型2和类型1之间的区别。
差异以秒为单位,但您可以根据需要进行更改。
在这里您可以找到一个示例:http://sqlfiddle.com/#!3/600f9/24包含您的数据。
查询组的第一部分按日结果并求和。在子查询中,我们获得了类型2和类型1之间的区别。