2012-07-30 25 views
1

感謝您尋找。顯示最接近的日期,也不得休息

我試圖讓每個客戶拜訪之間的最小時間。通過下面的代碼,我可以得到每次訪問之間的時間量,但它會比較每個日期。我只需要最小的餘量,然後擺脫/隱藏所有其他人。

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 
  • 在TRANSACTION_DATE每個日期找到最近的日期是在 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 

我也是固定的連接語法使用正確的聯接語法,並改變了「喜歡」到「=」,因爲你沒有通配符。

可能有其他的方法來表達這一點,但這是標準的SQL。您應該指定您在問題中使用的數據庫。

如果您使用的是Oracle,那麼就請執行以下操作:

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 

其實,這是不完全正確的,因爲你必須要空值考慮了nexttd和prevtd。但是,這個想法很簡單。領先和滯後功能可讓您進行prev或文本交易,然後您可以執行任何您想要的最低限度的操作 - 或從記錄中獲取所需的任何其他信息。

+0

謝謝! 如果我也想對結果查詢你將如何做到這一點的日期?我一直在嘗試,但只是「列明確定義」錯誤。 我正在使用Oracle。 – Regan 2012-07-30 02:30:37