22,207
社区成员
发帖
与我相关
我的任务
分享
; WITH CTE_Log AS (SELECT Location, [Date], ROW_Number() OVER(ORDER BY [Date]) AS RN FROM LocationLog )
SELECT S.Location, CONVERT(Decimal(7,2),SUM(S.Stay)/60.00/24.00) AS TotalDays
FROM
(SELECT a.Location, a.[Date], DateDiff(minute, a.[Date], b.[Date]) AS Stay
FROM CTE_Log a INNER JOIN CTE_Log b ON a.RN = b.RN-1 ) S
GROUP BY S.Location
create table travel
(location varchar(10),[date] varchar(10))
insert into travel
select 'PRC','20100101' union all
select 'PRC','20100102' union all
select 'PRC','20100104' union all
select 'USA','20100110' union all
select 'USA','20100118' union all
select 'UK','20100120' union all
select 'UK','20100120' union all
select 'UK','20100123' union all
select 'DE','20100124' union all
select 'FR','20100125' union all
select 'FR','20100201' union all
select 'PRC','20100203' union all
select 'PRC','20100203' union all
select 'TW','20100205'
with t as
(select location,[date],row_number() over(order by [date]) 'rn'
from travel),
u as
(select a.location,a.[date],row_number() over(order by a.rn) 'rn'
from t a
left join t b on a.rn=b.rn+1
where a.location!=b.location or b.rn is null)
select location,sum(d) 'days'
from
(select a.location,isnull(datediff(d,a.[date],b.[date]),1) 'd'
from u a
left join u b on a.rn=b.rn-1) t
group by location
order by (select min(rn) from t c where c.location=t.location)
/*
location days
---------- -----------
PRC 11
USA 10
UK 4
DE 1
FR 9
TW 1
(6 row(s) affected)
*/