2

我有一个包含列的表(没有索引):unique_id, subscriber_id, note, date_note_created (mm/dd/yyyy hh:mm:ss am), officer_making_note. Asubscriber_id每月可以有多个由不同官员制作的笔记。

我想有效地创建一个视图,该视图保存每个月的最后一条记录,每个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为期一个月,没有重复。

4

2 回答 2

2

我的猜测是您使用的是 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

要创建视图,您只需使用create view as语句。

于 2012-12-30T20:52:22.483 回答
0

尝试ROW_NUMBER窗口函数,如下所示:

select *
from ( 
   select subscriber_id
        , note, date_note_created, officer_making_note
        , ROW_NUMBER () OVER (PARTITION BY subscriber_id
                              ORDER BY date_note_created DESC) as rn
   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 lower(note) LIKE '%a%'
           or lower(note) like '%b%' 
           or lower(note) like '%c%' 
           or lower(note) like '%d%')
   )  xx
where rn = 1;
于 2012-12-30T20:43:21.567 回答