日期:2014-05-18  浏览次数:20526 次

请教统计7天内多次数据的sql如何写,谢谢
数据库里有工单记录,字段有客户号和建单时间
现要统计去年同一客户在7天内报修两次以上的比例,即:7天内有两次(含两次)以上的工单数/总工单数
请教这个sql如何写,谢谢

------解决方案--------------------
-- 按客户id分组,分别给每个客户的工单编号
select ROW_NUMBER() over(partition by customer_id order by id) row_num, * into #t from t3

-- 查询7天之内有2次以上工单的客户
select * from #t t1
inner join #t t2 on t1.customer_id = t2.customer_id and t1.row_num = t2.row_num - 1
where t1.dt >= DATEADD(day, -7, t2.dt)
------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null 
drop table [test]
create table [test](
[客户号] varchar(2),
[建单时间] datetime,
[建单内容] varchar(3)
)
insert [test]
select '01','2011.01.01','aaa' union all
select '02','2011.01.01','bb' union all
select '03','2011.01.02','ccc' union all
select '01','2011.01.03','ddd' union all
select '04','2011.01.04','eee' union all
select '05','2011.01.05','fff' union all
select '03','2011.01.08','ggg' union all
select '06','2011.01.09','hhh' union all
select '02','2011.01.11','iii'


select ltrim(COUNT([客户号]))+'/'+ltrim((select COUNT(*) from test)) as 比例
from(select [客户号],COUNT([客户号]) as times from test a
where exists(select 1 from(
select 客户号,MIN([建单时间]) as [建单时间] from test b group by [客户号])b
where a.建单时间<=dateadd(dd,6,b.建单时间) and a.客户号=b.客户号)
group by [客户号] having count(*)=2)c
/*
比例
2/9
*/