2012-07-30 3 views
1

Thanks for looking.가장 가까운 날짜를 표시하고 나머지는 표시하지 않습니다.

고객 당 방문 간 시간을 최소화하려고합니다. 아래의 코드를 통해 각 방문 사이의 시간이 표시되지만 모든 날짜를 비교합니다. 나는 가장 작은 마진을 필요로하고 다른 모든 것을 없애거나 숨길 수 있습니다. TRANSACTION_DATE의 각 날짜에 대한

select a.account_id, a.transaction_id, b.transaction_date , a.transaction_date,   round(a.transaction_date - b.transaction_date, 0) as Time_between 
from time_between_trans a, time_between_trans b 
where a.transaction_date > b.transaction_date 
and a.account_ID like '717724' 
and a.account_id = b.account_id 
  • 은 trasactions에 가장 가까운 날짜를 찾을

  • 그들은 같은 ACCOUNT_ID이어야하고, 둘째 날은 첫째

  • 이후에 을해야합니다

답변

1

검색어에 그룹을 추가해야합니다.

select a.account_id, a.transaction_id, min(time_between) as min_time_between 
from (select a.account_id, a.transaction_id, b.transaction_date, a.transaction_date, 
      round(a.transaction_date - b.transaction_date, 0) as Time_between 
     from time_between_trans a join 
      time_between_trans b 
      on a.transaction_date > b.transaction_date and 
       a.account_ID ='717724' and 
       a.account_id = b.account_id 
    ) a 
group by a.account_id, a.transaction_id 

와일드 카드가 없기 때문에 조인 구문을 수정하여 올바른 조인 구문을 사용하고 "like"를 "="로 변경했습니다.

다른 표현 방법이 있지만 표준 SQL입니다. 귀하의 질문에 사용중인 데이터베이스를 지정해야합니다.

Oracle을 사용하는 경우, 바로 다음을 수행하십시오 당신이 nexttd 및 prevtd에 대한 계정에 널 (NULL)을해야하기 때문에

select a.*, 
     (case when nextdt - transaction_date) < transaction_date - nextdt 
      then nextdt - transaction_date) 
      else transaction_date - nextdt 
     end) as mintime 
from (select a.*, 
      lead(transaction_date, 1) over (partition by account_id order by transaction_date) as nexttd, 
      lag(transaction_date, 1) over (partition by account_id order by transaction_date) as prevtd 
     from time_between_trans a 
    ) a 

사실이 매우 정확하지 않습니다. 그러나 그 아이디어는 간단합니다. 리드 및 래그 기능을 사용하면 이전 또는 텍스트 트랜잭션을 수행 한 다음 최소값을 찾으려는 모든 작업을 수행 할 수 있습니다. 또는 레코드에서 원하는 다른 정보를 얻을 수 있습니다.

+0

감사합니다. 결과 검색어에 날짜를 사용하고 싶다면 어떻게해야합니까? 나는 노력했지만 단지 "애매하게 정의 된 열"에 대한 오류를 얻는다. Oracle을 사용하고 있습니다. – Regan

관련 문제