select t1.ID,max(t1.bc) as "本次消费时间",max(t2.sc) as "上次消费时间" from( select ID, case when rn=1 then XFtime else null end as bc from( select row_number() over(partition by ID order by XFtime desc) as rn, ID,XFtime from VIP ) ) t1 join ( select ID, case when rn=2 then XFtime else null end as sc from( select row_number() over(partition by ID order by XFtime desc) as rn, ID,XFtime from VIP ) ) t2 on t1.ID=t2.ID group by t1.ID
我用的是Oralce可能MSSQL有的写法不一样。
TSql 都差不多了 你的思路 我了解了 我是 top2 except top1 来得到上次消费时间
top1就是本次消费时间
建了2张临时表 分别存放两次的时间 不过效率很低 600多条记录 查了13秒
@Thomas Anderson:
group by 放里面,sql2005,2000多条瞬间:
select t1.ID,t1.bc as "本次消费时间",t2.sc as "上次消费时间" from( select ID, max(case when rn=1 then XFtime else null end) as bc from( select row_number() over(partition by ID order by XFtime desc) as rn, ID,XFtime from VIP ) t group by id ) t1 join ( select ID, max(case when rn=2 then XFtime else null end) as sc from( select row_number() over(partition by ID order by XFtime desc) as rn, ID,XFtime from VIP ) t group by id ) t2 on t1.ID=t2.ID