[英]how to retrieve previous month latest date and current month latest dates in sql
create table imsi_data(account varchar2(20)not null,imsi number(10),seqno number(20) not null,package_id number(10),event_date date)
insert into imsi_data values('10001',123456,09,164,add_months((sysdate),-2));
insert into imsi_data values('10001',123456,09,164,add_months((sysdate-1),-2));
insert into imsi_data values('10001',123456,09,164,add_months((sysdate-2),-2));
insert into imsi_data values('10001',123456,10,165,add_months((sysdate),-1));
insert into imsi_data values('10001',123456,10,165,add_months((sysdate-1),-1));
insert into imsi_data values('10001',123456,10,165,add_months((sysdate-2),-1));
select * from imsi_data
ACCOUNT IMSI SEQNO PACKAGE_ID EVENT_DATE
1 10001 123456 9 164 9/4/2015 4:17:06 AM
2 10001 123456 9 164 9/3/2015 4:17:18 AM
3 10001 123456 9 164 9/2/2015 4:18:16 AM
4 10001 123456 10 165 10/4/2015 4:18:34 AM
5 10001 123456 10 165 10/3/2015 4:23:23 AM
6 10001 123456 10 165 10/2/2015 4:23:31 AM
Expected output: I need to see the data in one row, getting the latest seq no details and lastusagedate( as Previous seqno(9) latest date)预期输出:我需要在一行中查看数据,获取最新的 seq no details 和 lastusagedate(作为 Previous seqno(9) 最新日期)
ACCOUNT IMSI SEQNO PACKAGEID LastUsageDate CurrentUsageDate
10001 123456 10 165 9/4/2015 4:17:06 AM 10/4/2015 4:18:34 AM
My sql is here:我的 sql 在这里:
select account,
imsi,
lastusage_date,
current_date,
package_id,
seqno
from (
select ce.package_id,
ce.seqno,
ce.account,
ce.IMSI,
lag(ce.event_date) over(partition by ce.IMSI, ce.seqno order by ce.IMSI, ce.event_date desc) lastusage_date,
ce.event_date current_date,
row_number() over(partition by ce.imsi, ce.seqno order by ce.event_date desc) rn
from imsi_data ce
where ce.account = '10001' and ce.seqno in (10, 09)
group by ce.account, ce.seqno, ce.imsi, ce.event_date, ce.package_id)
where rn =1
This is getting lastusagedate as null.这将 lastusagedate 设为 null。 But i should get the previous seq max event_date can any one pls help me out:但我应该得到之前的 seq max event_date 任何人都可以帮助我:
You can try the following:您可以尝试以下操作:
select
ce.account,
ce.IMSI,
ce.seqno,
ce.package_id,
(
select
max(prev_seq_date_ivw.event_date) ev_date
from
imsi_data prev_seq_date_ivw
where
prev_seq_date_ivw.seqno = (
select
max(prev_seq_ivw.seqno)
from
imsi_data prev_seq_ivw
where
prev_seq_ivw.seqno < ce.seqno
)
) last_usage_date,
max(ce.event_date) current_usage_date
from imsi_data ce
where ce.account = '10001' and ce.seqno in (10, 09)
group by
ce.account,
ce.IMSI,
ce.seqno,
ce.package_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.