其实还可以有另外一个名字:如何在rs中基于关系库取得last nonempty
【需求描述】:
ps:该需求来自群成员“半截烟头”
有一个表,里面按月记录了数据,现在要这样做,提供一个月份参数,取每个分组当前月份的数据,如果找不到,就取该分组内离该月份最近一个有数的月份的数据。
如下demo数据:
OBJ_ID Year month value
1 2009 1 100.00
1 2009 2 200.00
1 2009 3 300.00
1 2009 4 400.00
2 2009 1 15
2 2009 2 20
如果查询条件year=2009,month=4那么结果就是:
OBJ_ID Year month value
1 2009 4 400.00
2 2009 2 20
基本上这样的需求就是按照obj_id取满足条件的last nonempty。
在数据库(sql server)中写sql是这样的:
select a.obj_id,
a.year as yr
a.month as mon,
a.sum(value) as value
from object_info a,
(select obj_id,
max(month) as mon
from dbo.object_info
where year=2009 and month<=4
group by obj_id) b
where a.year=2009 and a.obj_id=b.obj_id and a.mon=b.mon
group by obj_id,year,month
order by obj_id,month
那么在rs中应该怎样实现呢?
收起