我有一个表(没有索引),其中包含以下列:unique_id
、subscriber_id
、note
、date_note_created (mm/dd/yyyy hh:mm:ss am)
,officer_making_note
。一个 subscriber_id
每月可以有多个由不同官员制作的注释。
我想有效地创建一个 View ,保存每个 subscriber_id
每月最后一条记录,其中注释类似于 '%some string%'
。
select * from
(select subscriber_id, note, date_note_created, officer_making_note
from table
where user_id = v_sub_id
and date_note_created between to_date(v_monthstart, 'mm/dd/yyyy')
and to_date(v_monthend, 'mm/dd/yyyy')
AND (LOWER (note) LIKE '%z%'
or (note) LIKE '%a%'
or lower(note) like '%b%'
or lower(note) like '%c%'
or lower(note) like '%d%')
order by date_note_created desc)
where rownum = 1;
上面的代码显示了我为一个 subscriber_id
实现这一目标一个月而没有重复的做法。
最佳答案
我的猜测是您正在使用 Oracle。这使您可以访问分析功能。
由于您正在查找多个月份和所有订阅者,因此我删除了 where
子句中对月份和订阅者 ID 的限制。我还添加了月份标识符(作为“YYYY-MM”格式的字符串):
select *
from (select subscriber_id, note, date_note_created, officer_making_note, to_char(date_note_created, 'YYYY-MM') as mon
row_number() over (partition by subscriber_id, to_char(date_note_created, 'YYYY-MM')
order by date_note_created desc) as seqnum
from table
where /* user_id = v_sub_id and */
/* date_note_created between to_date(v_monthstart, 'mm/dd/yyyy') and to_date(v_monthend, 'mm/dd/yyyy') AND */
(LOWER (note) LIKE '%z%' or (note) LIKE '%a%' or lower(note) like '%b%' or lower(note) like '%c%' or lower(note) like '%d%'
)
)
where seqnum = 1
要创建 View ,您只需使用 create view as
语句即可。
关于sql - 获取每个subscriber_id 每月的最大(日期)记录。每月不返回重复的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14094381/