我现在有两个表,
a表:(时间)
| date |
| 19990101 |
| 19990102 |
| ... |
| 20000101 |
b表:(评级变更记录)
startdate
| enddate | credit |
| 19980901 | 19990201
| aaa |
| 19990201 | 19990302 | aa |
| ... | ... | ... |
| 19990903 | null | baa |
现在想写段sql语句生成c表,规则是利用b表的信用评级变更记录对a表每条记录进行评级,即生成一个表格,包含A的所有数据,并且对每个date数据,如果它位于b表某个(statdate, enddate)左闭右开区间,则给该条记录添加相应的credit字段。如果enddate为null,表示至今评级未改变。
我很菜,只会先把两者cross join,然后算出一个flag变量来判断date是否在区间中。请问有什么更有效的办法?
我的方法:
select * from
(
select a.data, b.credit,
case
when a.date > =b.startdate and ( a.date <=b.enddate or b.enddate is null) then '1'
else '0'
end as flag
from a cross join b
) c
where c.flag='1'