簡體   English   中英

將行加入上一個最近的日期行

[英]Join Row to Previous Closest Date Row

數據庫數據:

id | account | date       | random_data
1  | 1       | 01/01/2013 | qw
2  | 2       | 05/01/2013 | er
3  | 2       | 09/01/2013 | ty
4  | 1       | 05/01/2013 | ui
5  | 2       | 11/01/2013 | op
6  | 1       | 12/01/2013 | as

嗨,假設我們要從2013年5月1日開始記錄-請注意,第一行的prev_date仍顯示比05/01更早的日期,這意味着仍需要搜索整個表。

結果數據:

account | cur_date   | random_data | prev_date  | prev_rand_data
1       | 05/01/2013 | ui          | 01/01/2013 | qw
1       | 12/01/2013 | as          | 05/01/2013 | ui
2       | 05/01/2013 | er          | null       | null
2       | 09/01/2013 | ty          | 05/01/2013 | er
2       | 11/01/2013 | op          | 09/01/2013 | ty

因此,我不確定什么可以用於此最佳,最優化的查詢。 我不反對使用php解決方案,但是不確定是否會有更好的解決方案。 我考慮過的一些想法:

  1. 同一張桌子上的某種聯接-雖然不確定如何
  2. 選擇子查詢-

    select date as cur_date , (select max(date) from table where date < cur_date group by account) as prev_date... -這似乎非常耗費時間

  3. 會話變量-在每一行上設置一個會話變量,它將是下一行的上一個數據,例如

    select date as cur_date , @prev_date as prev_date , @prev_date:=date...

有沒有人對這種問題有任何經驗,有沒有好的解決方案? 我所提出的任何想法在將來都會引起問題嗎?

我將使用sql和應用程序代碼的組合。 由於我不是PHP程序員,因此我將僅描述用於應用程序部分的邏輯。

首先查詢。

select account, date, random_data
from thetable
where date >= YourDateVariable

union

select account, date, random_data
from thetable join
(select account acc, max(date) maxdate
from thetable
where date <= YourDateVariable
group by account) x on account = acc and date = max(date)
where date <= YourDateVariable

order by account, date

對於應用程序代碼,請執行以下操作:

Set a variable called ThisAccount to 0.
Set a row counter variable to 0.
Create an empty 2D array
Start looping through your query results
Put the account value and random data into the first two columns
    of the next available row of the array
Compare the account value to the value of the ThisAccount variable.  
   If they are the same, get the previous date and random data from 
   the previous row in the array.
Set the ThisAccount variable to the current account value.
Increment your row counter variable
End of loop.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM