【问题标题】:ROWNUM and DISTINCT in oracleoracle 中的 ROWNUM 和 DISTINCT
【发布时间】:2016-12-16 13:25:10
【问题描述】:

我在尝试编写以下查询时遇到了麻烦:

SELECT id,
       contractnumber,
       partyid,
       entity,
       product,
       fecha
FROM (
  SELECT DISTINCT (contractdet.id),
         contractdet.contractnumber,
         contractdet.partyid,
         contractdet.entity,
         contractdet.product,
         contractdet.fecha,
         ROWNUM AS rnumber
  FROM contractdet
    INNER JOIN contractcust ON contractcust.contractdet_id = contractdet.id
    INNER JOIN customerdet ON customerdet.partyid = contractdet.partyid
  WHERE TO_CHAR(contractdet.fecha, 'YYYYMM') <= TO_CHAR(ADD_MONTHS(TO_DATE(20160828, 'YYYYMMDD'), -3), 'YYYYMM')
    AND contractdet.product = 'TC'
  ORDER BY contractdet.id ASC
)
WHERE rnumber BETWEEN ?   AND ?
ORDER BY id

我在一段 java 代码中使用它来分页进程,每次重复查询并检索 1000 个结果。我遇到的主要问题是 DISTINCT 顺序仅适用于我所在的时间间隔,而不适用于整个结果集,因此当我混合我所做的所有查询的输出时,它会检索重复的行。

【问题讨论】:

  • 努力格式化您的查询。
  • DISTINCTNOT 一个函数。它始终适用于查询中的所有列。
  • 另外:TO_DATE(20160828, ..) 是错误的。 to_date() 需要一个字符串 (varchar) 而不是数字,你根本不需要 to_date()。表达式也可以简化为ADD_MONTHS(DATE '2016-08-28', -3)
  • @pedrero 。 . .为什么说:DISTINCT (contractdet.id)?括号表示没有。正如 a_horse_with_no_name 所说,distinct 适用于所有列。
  • 什么版本的Oracle?

标签: sql oracle distinct rownum


【解决方案1】:

您可以在 Java 中的 SQL 中使用 CTE 吗?

这是一个例子:

with distinctRecords as (
    select distinct myCol, rownum rnum
    from myTable
    order by myCol
)
select *
from distinctRecords
where rnum between ? and ?; 

【讨论】:

  • 也就是说,实际上,OP 在使用内联视图时正在做什么。无论您是在 with 子句还是在 from 子句中声明子查询,它仍然是一个子查询(并且由于 rownum 的存在而不能取消嵌套)。
【解决方案2】:

你可以这样做:

with t as (
      <your subquery here without the `distinct`>
     )
select t.*
from (select t.*,
             row_number() over (partition by id order by id) as seqnum
      from t
     ) t
where seqnum = 1;

这将为每个id 选择一个任意行。您可以通过更改子查询中的order by 来控制选择哪一行(比如最旧的或最新的)。

【讨论】:

    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2014-04-05
    • 2018-06-01
    • 2019-03-24
    相关资源
    最近更新 更多