【问题标题】:how to get unique row numbers in sql如何在sql中获取唯一的行号
【发布时间】:2023-03-26 04:54:02
【问题描述】:

如何仅从以下查询的结果中获取第一行。我需要每个日期的最新记录,所以我按 created_date 进行了分区。但是在某些地方,我得到了相同的行号并且无法获得预期的输出。请找到以下查询、当前输出和预期输出。

需要进行哪些更改才能获得预期的输出?谢谢。

WITH ctetable
AS (
    SELECT created_date BPMDate
        ,tenor
        ,row_number() OVER (
            PARTITION BY created_date ORDER BY created_date DESC
            ) rw
    FROM table1 a
    INNER JOIN table2 b ON a.case_id = b.case_id
        AND a.eligible_transaction = 'true'
        AND to_date(a.created_date) >= '2020-10-01'
        AND to_date(a.created_date) <= '2020-10-05'
        AND case_status = 'Completed'
    )
SELECT BPMDate
    ,Tenor
    ,rw
FROM ctetable

当前输出:

date                tenor   rw
2020-10-05 13:24:15.0   1W      1
2020-10-05 12:15:43.0   1Y      1
2020-10-05 12:15:43.0   1Y      2
2020-10-01 13:30:59.0   1W      1
2020-10-01 13:30:59.0   1W      2

预期输出:

 date               tenor   rw
2020-10-05 13:24:15.0   1W      1
2020-10-01 13:30:59.0   1W      1

问候, 维雷什

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。

标签: sql datetime where-clause greatest-n-per-group


【解决方案1】:

那就是:

with ctetable as  (  
    select created_date, bpmdate, tenor, 
        row_number() over (partition by date(created_date) order by created_date desc ) rn
    from table1 a  
    inner join table2 b
        on  a.case_id = b.case_id 
        and a.eligible_transaction = 'true' 
        and to_date(a.created_date) >=  '2020-10-01' 
        and to_date(a.created_date) <=  '2020-10-05' 
        and case_status='completed'
    ) 
select bpmdate,tenor,rw
from ctetable
where rn = 1

对原始代码的更改:

  • 需要去掉窗口函数partition by子句中日期的时间部分;您没有告诉您使用的是哪个数据库:我使用了date(),但您的数据库中的功能可能不同(Oracle 中的trunc(),Postgres 中的date_trunc(),等等)

  • 外部查询需要过滤等于1的行号

【讨论】:

    【解决方案2】:

    你似乎想要每天第一行:

    select BPMDate, Tenor, rw
    from (select t.*,
                 row_number() over (partition by trunc(bpmdate) order by bpmdate) as seqnum
          from ctetable
         ) t
    where seqnum = 1;
    

    注意:我不知道你的数据库是否支持trunc(),但这只是一种从列中提取日期的方法。

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 2022-01-01
      相关资源
      最近更新 更多