sql - 获取每个subscriber_id 每月的最大(日期)记录。每月不返回重复的 ID

标签 sql oracle oracle11g

我有一个表(没有索引),其中包含以下列:unique_idsubscriber_idnotedate_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/

相关文章:

sql - rails 种子 : How to truncate DB table?

sql - 在 SQL 对象表中的子类型特定属性上创建索引

java - tableView(JavaFX) 填写表单 ObservableList 不起作用

mysql - Oracle 数据库的扩展和高可用性

sql - 如何查找查询执行的次数?

php - Laravel 根据投票显示前 5 个笑话

mysql - 所有连接末尾的“where”子句

sql - 如何知道事务方案何时可序列化?

sql - ORA-00054: 资源繁忙并使用指定的 NOWAIT 获取

oracle - 如何在sql中查找以 '%'开头的名称