作者cutekid (可爱小孩子)
看板Database
标题Re: [SQL ] 计算次数 连续30天内只能算一次
时间Tue Mar 28 01:14:18 2017
附上 MSSQL 解法(应该跟 db2 大同小异):
-- 测资部份(红色是我新增的部份)
select * into #t
from (
select cast('2010-01-04' as datetime) as date
union all
select '2009-12-21'
union all
select '2009-12-18'
union all
select '2009-12-18'
union all
select '2009-11-16'
union all
select '2009-10-31'
union all
select
'2009-10-16'
union all
select
'2009-09-15'
) t1
-- 递回处理
;with tb1 as (
select dateadd(day,-30,max(date)) as beginDate,
max(date) as endDate,
cast(1 as bigint) as num
from #t
union all
select dateadd(day,-30,t1.date),
t1.date,
row_number() over (order by t1.date desc)
from #t t1 inner join tb1 t2
on t2.num = 1 and t1.date < t2.beginDate
)
-- 运算结果
select endDate from tb1 where num = 1
drop table #t
※ 引述《atm (Against the current)》之铭言:
: 资料库名称: db2
: 内容/问题描述:从最後一笔计算次数 30天内都算同一次
: 以下面例子来说 最後一笔2010-01-04往前推30天:2009-12-05
: 所以在2009-12-05~2010-01-04这段期间发生的资料当做一笔
: 依此类推 2009-11-16 和2009-10-31这两笔记录也只当做一笔
: 故计算结果=2 试着用递回结果没有成功...请问该如何得到答案?
: date
: 2010-01-04
: 2009-12-21
: 2009-12-18
: 2009-12-18
: 2009-11-16
: 2009-10-31
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 223.141.120.126
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Database/M.1490634861.A.010.html
1F:→ atm: thank you ! 03/29 22:31