请教统计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)
[解决办法]
--> 测试数据:[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 allselect '02','2011.01.01','bb' union allselect '03','2011.01.02','ccc' union allselect '01','2011.01.03','ddd' union allselect '04','2011.01.04','eee' union allselect '05','2011.01.05','fff' union allselect '03','2011.01.08','ggg' union allselect '06','2011.01.09','hhh' union allselect '02','2011.01.11','iii'select ltrim(COUNT([客户号]))+'/'+ltrim((select COUNT(*) from test)) as 比例from(select [客户号],COUNT([客户号]) as times from test awhere exists(select 1 from(select 客户号,MIN([建单时间]) as [建单时间] from test b group by [客户号])bwhere a.建单时间<=dateadd(dd,6,b.建单时间) and a.客户号=b.客户号)group by [客户号] having count(*)=2)c/*比例2/9*/