我有t_cust表,我想显示客户的最新账单月和账单金额。 我写了查询,但对于大数据,它将花费很多时间。有任何简单的 寻找最新法案月的逻辑?
create table t_cust
(
cust_id varchar2(3),
b_year varchar2(4),
b_month varchar2(2),
b_amount number
);
insert into t_cust values('ABC','2015','11',100);
insert into t_cust values('ABC','2015','12',200);
insert into t_cust values('ABC','2016','01',300);
insert into t_cust values('XYZ','2016','01',1000);
insert into t_cust values('XYZ','2016','02',2000);
insert into t_cust values('XYZ','2016','03',3000);
commit;
select cust_id,substr(to_date(b_year*100+b_month,'YYYYMM'),4)latest_bill_mth,b_amount bill_amount
from t_cust
where (cust_id,b_year*100+b_month) in (
select cust_id,max(b_year*100+b_month)
from t_cust
group by cust_id
);
答案 0 :(得分:0)
看起来像Oracle,所以只需使用ROW_NUMBER / RANK:
select ...
from
(
select ...
,row_number()
over (partition by t_cust
order by year desc, month desc) as rn
) dt
where rn = 1