各位大神,请教一下
有个数据表
id money time
1 200 20130101
2 1 20130212
1 3 20130312
3 353 20121201
2 4 20121103
4 32 20130201
4 20 20130205
1 0.5 20130101
.. .. ..
如何统计连续六个月月均总额低于200的ID啊?SQL语句请教
有个数据表
id money time
1 200 20130101
2 1 20130212
1 3 20130312
3 353 20121201
2 4 20121103
4 32 20130201
4 20 20130205
1 0.5 20130101
.. .. ..
如何统计连续六个月月均总额低于200的ID啊?SQL语句请教
建议用存储过程来实现
连续6个月 月均总额低于200 是指 :1, sum(连续6个月)/6 < 200
2, 月 < 200 的连续6个月都是?
insert @t select 1, 200, '20130101'
union all select 2 ,1, '20130212'
union all select 1 ,300, '20130312'
union all select 3 ,353, '20121201'
union all select 2 ,4, '20121103'
union all select 4 ,32, '20130201'
union all select 4 ,20, '20130205'
union all select 1 , 0.5, '20130101'
union all select 1, 1500,'20130202'select * from @t order by id--数据有限,以连续三个月大于200为例
declare @m int
set @m=2
;with fc as
(
select id, SUM(m) m,LEFT(t,6) t,COUNT(*) c from @t group by id,LEFT(t,6)
)
,fc1 as
(
select a.id,a.t at,b.t bt from fc a
join fc b
on a.id=b.id and DATEDIFF(mm,a.t +'01',b.t + '01')=@m-1
)
select a.id,at,bt from fc1 a
join fc b
on a.id=b.id and t between at and bt
where m/c>=200
group by a.id,at,bt
having COUNT(distinct t)=@m
/*
无数据
*/
--将@m改为2,即连续2个月大于200
/*
1 201302 201303表示id为1, 在201302到201303区间的两个月,是连续大于200的
*/
连续6个月小于200的同理。有些月没数据的,不知道你要如何处理, 所以就没给你写例子。