2017-05-19 8 views
0

데이터 세트에서 증가하는 서브 시퀀스를 찾는 이전 질문이 뒤 따른다. SQL에서 n 번 증가하는 서브 시퀀스 찾기.

Finding out the increasing subsequence in sql

는 어떻게 당 할 수있는, 내가

select x, y 
from (select max(x) over (order by y desc) as x_max, x, max(y) over (order by x desc) as y_max, y 
    from table 
    order by y desc, x desc) t 
where t.x = t.x_max and t.y = t.y_max 
order by y desc, x 

지금 내 질문은 쿼리를 적용 할 수 있습니다

x | y 
-----+----- 
    94 | 985 
    73 | 940 
469 | 865 
115 | 864 
366 | 862 
525 | 842 
448 | 837 
318 | 832 
507 | 826 
244 | 758 
217 | 741 
207 | 732 
    54 | 688 
426 | 605 
108 | 604 
610 | 587 
142 | 581 
765 | 579 
102 | 572 

에서 결과

x | y 
-----+----- 
    94 | 985 
469 | 865 
525 | 842 
610 | 587 
765 | 579 

를 얻으려면 이 연산을 n 번, 즉 x의 2 번째, 3 번째, ..., n 번째 증가 서브 시퀀스를 찾는다. 일반적인 생각은 원래 테이블에서 첫 번째 연산의 결과를 가져 와서 나머지 점에 대한 쿼리를 수행하는 것입니다. 내 예에 따라서

, 첫 수술 후, 우리는 우리가

x | y 
-----+----- 
    73 | 940 
115 | 864 
366 | 862 
448 | 837 
507 | 826 

을 얻을 그리고

에 작업을 수행,

x | y 
-----+----- 
    73 | 940 
115 | 864 
366 | 862 
448 | 837 
318 | 832 
507 | 826 
244 | 758 
217 | 741 
207 | 732 
    54 | 688 
426 | 605 
108 | 604 
142 | 581 
102 | 572 

을 남은 포인트가하고 조회를 다시 적용

x | y 
-----+----- 
318 | 832 
244 | 758 
217 | 741 
207 | 732 
    54 | 688 
426 | 605 
108 | 604 
142 | 581 
102 | 572 

등등. 나는이 최적의에서까지 & 사소한 아니다 즉

x | y 
-----+----- 
    73 | 940 
    94 | 985 
115 | 864 
366 | 862 
448 | 837 
469 | 865 
507 | 826 
525 | 842 
610 | 587 
765 | 579 
+0

재귀 쿼리 평가? https://www.postgresql.org/docs/current/static/queries-with.html –

답변

0

, 이러한 쿼리 검색 및 Y 내림차순으로 순서를 모든 점 조합하고 싶지만, 당신은 참으로 재귀 CTE를 사용하여이 작업을 수행 할 수

with recursive r as(
    (select x, y, (running_x_max <> x)::int grp, 0 iteration 
    from  (select *, max(x) over (order by y desc) running_x_max 
      from xy) t 
    order by 3, 2 desc) 
    union all 
    (select x, y, grp + (running_x_max <> x)::int, iteration + 1 
    from  (select *, max(x) over (order by y desc) running_x_max 
      from r 
      where grp > iteration) t 
    order by 3, 2 desc) 
) 
select x, y, grp 
from  r 
where grp = iteration 
order by 3, 2 desc, 1 

http://rextester.com/JDYJ58330