oracle—如何从已经使用distinct的sql查询中仅返回唯一行

vktxenjb  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(372)

我知道在特定列上使用distinct运算符只能返回唯一的行。我成功地使用了列上的distinct运算符进行查询。现在,我希望查询只返回其余列的不同结果。例如下面的查询:

Select distinct pl.oid, pr.npd, sch.shortstringvalue
from sonpda_rdb.jpipelinesystem pl
join sonpda_rdb.xsystemhierarchy xsys1 on xsys1.oidorigin = pl.oid
join sonpda_rdb.jnameditem it1 on it1.oid = pl.oid
join sonpda_rdb.jrtepiperun pr on pr.oid = xsys1.oiddestination
join sonpda_rdb.jnameditem it2 on it2.oid = pr.oid
join sonpda_rdb.xownsparts xop on xop.oidorigin = pr.oid
join sonpda_rdb.jrtestockpartoccur stckprt on stckprt.oid = xop.oiddestination
join sonpda_rdb.xmadefrom xmf on xmf.oidorigin = stckprt.oid
join sonpda_rdb.jdpipecomponent pipcmp on pipcmp.oid = xmf.oiddestination
join sonpda_rdb.cl_schedulethickness sch on sch.valueid = pipcmp.firstsizeschedule
where it1.itemname = 'C-8001'
order by pr.npd desc;

给出了下表所示的结果
000334570000000000625CE8F235CF10F 2.0 s-40s型
0003345700000000012BADECFA5B4804 2.0 s-40s型
000334570000000000625CE8F235CF10F 1.0 s-40s
0003345700000000012BADECFA5B4804 1.0 s-40s型
0003345700000000014BAB9B0FB5B7704 1.0 s-40s
根据查询的第二列和第三列,只有两个不同的行。如何修改查询以只返回这两个不同的行?

2eafrhcq

2eafrhcq1#

一种方法使用 row_number() :

with q as (
      <your query here>
     )
select q.*
from (select q.*,
             row_number() over (partition by npd, shortstringvalue order by oid desc) as seqnum
      from q
     ) q
where seqnum = 1;

从oracle 12c开始,您还可以使用:

select . . .
from . . .
order by row_number() over (partition by npd, shortstringvalue order by oid desc)
fetch first 1 row with ties;
sd2nnvve

sd2nnvve2#

请使用下面的查询。你必须使用 row_number() .

select 
    oid, npd, shortstringvalue 
from
    (Select distinct 
         pl.oid, pr.npd, sch.shortstringvalue, 
         row_number() over (partition by pr.npd, sch.shortstringvalue order by sch.shortstringvalue) as rnk
     from 
         sonpda_rdb.jpipelinesystem pl
     join 
         sonpda_rdb.xsystemhierarchy xsys1 on xsys1.oidorigin = pl.oid
     join 
         sonpda_rdb.jnameditem it1 on it1.oid = pl.oid
     join 
         sonpda_rdb.jrtepiperun pr on pr.oid = xsys1.oiddestination
     join 
         sonpda_rdb.jnameditem it2 on it2.oid = pr.oid
     join 
         sonpda_rdb.xownsparts xop on xop.oidorigin = pr.oid
     join 
         sonpda_rdb.jrtestockpartoccur stckprt on stckprt.oid = xop.oiddestination
     join 
         sonpda_rdb.xmadefrom xmf on xmf.oidorigin = stckprt.oid
     join 
         sonpda_rdb.jdpipecomponent pipcmp on pipcmp.oid = xmf.oiddestination
     join 
         sonpda_rdb.cl_schedulethickness sch on sch.valueid = pipcmp.firstsizeschedule
     where 
         it1.itemname = 'C-8001') query 
where 
    rnk = 1
order by 
    npd desc;

相关问题