从同一行中选择最大值和最小值按行/

时间:2016-12-08 20:10:28

标签: sql oracle

我需要用SQL解决后续问题(在Oracle DB上)

表A

COL1  COL2
a     1
b     84
c     5
d     90
e     9
f     11
g     22

我需要从表A中选择(选择表格A按col2排序DESCENDING criss-by-row WITH select table A by col2 ASCENDING)

这样最大的行后跟最小的行,依此类推......

类似的东西:

COL1  COL2
d     90   (most extreme maximum(1))
a      1   (most extreme minimum(1))
b     84   (most extreme maximum(2))
c      5   (most extreme minimum(2))
g     22   (most extreme maximum(3))
e      9   (most extreme minimum(3))
f     11   .. and so on.. 

我可以在PL / SQL中完成,但我需要在SQL中使用它。

非常感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

select a.*
from ((select a.*, row_number() over (order by col2 asc) as seqnum, 1 as ismax
       from a
      ) union all
      (select a.*, row_number() over (order by col2 desc) as seqnum, 0
       from a
      )
     ) a
order by seqnum, ismax desc;

答案 1 :(得分:1)

构建分拣机:

with 
--your data
tableA as
  (select 'a' as col1, 1 as col2 from dual
   union all
   select 'b' as col1, 84 as col2 from dual
   union all
   select 'c' as col1, 5 as col2 from dual
   union all
   select 'd' as col1, 90 as col2 from dual
   union all
   select 'e' as col1, 9 as col2 from dual
   union all
   select 'f' as col1, 11 as col2 from dual
   union all
   select 'g' as col1, 22 as col2 from dual
   union all
   select 'e' as col1, 4 as col2 from dual),

--get your stats
  aggs as
  (select col1, min(col2) as col2, 2 as sorter from tableA group by col1
   union all
  select col1, max(col2) as col2, 1 as sorter from tableA group by col1
  order by sorter)
   select distinct col1, col2
   from aggs
   order by col1;

以下基于您的评论的新答案

with aggs as
  (select col1, min(col2) as col2, 2 as sorter from 
  a   --your table name?
 group by col1
   union all
  select col1, max(col2) as col2, 1 as sorter from 
a   --your table name?
group by col1
  order by sorter)

   select distinct col1, col2
   from aggs
   order by col1;

答案 2 :(得分:0)

select    col1, col2
from      a
order by  least ( row_number() over (order by col2 desc),
                  row_number() over (order by col2) + 0.5
                )
;