日期:2014-05-18 浏览次数:20618 次
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[name] varchar(2),[tel] varchar(3),[departTime] datetime)
insert [tb]
select 1,'11','22','2012-07-17 00:00:00' union all
select 8,'ab','c','2012-07-17 00:00:00' union all
select 9,'ab','123','2012-07-17 00:00:00' union all
select 10,'ab','123','2012-07-18 00:00:00' union all
select 11,'ab','123','2012-06-13 00:00:00'
go
select name,tel,avg(dt) as [avg]
from
(
select *,
datediff(dd,departtime,isnull((select top 1 departtime from tb where name=t.name and tel=t.tel and departtime>t.departtime order by departtime),departtime)) as dt
from tb t
) t
group by name,tel
/**
name tel avg
---- ---- -----------
ab 123 11
11 22 0
ab c 0
(3 行受影响)
**/
------解决方案--------------------
CREATE TABLE #TEMP(ID INT,NAME VARCHAR(30),TEL VARCHAR(30), DEPARTTIME DATETIME) GO INSERT INTO #TEMP SELECT 1, '11', '22', '2012-07-17 00:00:00' UNION ALL SELECT 8 ,'AB', 'C' ,'2012-07-17 00:00:00' UNION ALL SELECT 9, 'AB', '123' ,'2012-07-17 00:00:00' UNION ALL SELECT 10, 'AB', '123', '2012-07-18 00:00:00' UNION ALL SELECT 11, 'AB', '123', '2012-06-13 00:00:00' GO SELECT NAME,TEL,AVG(DT) AS [AVG] FROM ( SELECT ID,NAME,TEL, DATEDIFF(DD,DEPARTTIME,ISNULL((SELECT TOP 1 DEPARTTIME FROM #TEMP WHERE NAME=T.NAME AND TEL=T.TEL AND ID != T.ID AND DEPARTTIME>=T.DEPARTTIME ORDER BY DEPARTTIME),DEPARTTIME)) DT FROM #TEMP T ) T GROUP BY NAME,TEL ORDER BY MIN(ID) DROP TABLE #TEMP GO ----------------------- 11 22 0 AB C 0 AB 123 11
------解决方案--------------------
--> 测试数据:[A1]
if object_id('[A1]') is not null
drop table [A1]
create table [A1](
[id] int,
[name] varchar(2),
[tel] varchar(3),
[departTime] datetime
)
go
insert [A1]
select 1,'11','22','2012-07-17 00:00:00' union all
select 8,'ab','c','2012-07-17 00:00:00' union all
select 9,'ab','123','2012-07-17 00:00:00' union all
select 10,'ab','123','2012-07-18 00:00:00' union all
select 11,'ab','123','2012-06-13 00:00:00'
go
;with t
as(
select
px=ROW_NUMBER()over(partition by [name],[tel] order by [departTime] asc),
*
from
[A1]
),
m as
(
select
px,
name,
tel,
[departTime],
0 as TotalDays
from
t
where
px=1
union all
select
a.px,
a.name,
a.tel,
a.[departTime],
DATEDIFF(dd,m.[departTime],a.departTime)
from
t a
inner join
m
on
a.px=m.px+1 and a.tel=m.tel
)
--select * from m
select
name,
tel,
AVG(TotalDays) as TotalDays
from
m
group by
name,tel
/*
name tel TotalDays
-----------------------------------
ab 123 11
11 22 0
ab c 0
*/