oracle

时间:2016-12-16 13:25:11

标签: sql oracle distinct rownum

我在尝试编写以下查询时遇到问题:

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命令仅适用于我所在的时间间隔,而不适用于整个结果集,所以当我混合我所做的所有查询的输出时,它会检索重复的行。

2 个答案:

答案 0 :(得分:0)

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

以下是一个例子:

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

答案 1 :(得分:0)

您可以这样做:

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来控制选择哪一行(比如最旧或最新)。