2016-02-15 64 views
2

讓我用一個例子來解釋。我有以下表格:在sql查詢中合併來自以前和當前記錄的數據

1. 2010 100  
2. 2011 200 
3. 2012 150 
4. 2013 300 

我需要設置像一個結果如下:

1. 2010 100 200 
2. 2011 200 150 
3. 2012 150 300 
4. 2013 300 500 

正如你所看到的,結果應該有第二列,其值是第一列以下記錄。我正在使用Delphi和BDE,因此使用本地SQL。

我沒有找到辦法做到這一點。如果這不能在本地SQL中完成,我想知道這是否可以在SQLite中完成

+0

'2010 100'是一列嗎? – tmutton

+1

我無法理解你在問什麼:( – fantaghirocco

+0

「2010 100」,「2011 200」在一個或兩個字段中? – tmutton

回答

0

沒有必要折磨sql - 添加計算列,運行數據集並將其初始化爲所需的值。運行向後不是一個常見的場景,所以我沒有檢查這個方法:

PriorValue := 0; 

with MyDataset do 
begin 
    Last; 
    PriorValue := <dataset>.FieldValue['MyValue_Col_1']; 
    // Note: you have to do something with the very last row; 
    Prior; 

    while not BOF do 
    begin 
    Edit; 
    FieldValues['MyValue_Col_2'] := PriorValue; 
    PriorValue := FieldValues['MyValue_Col_1']; 
    Prior; 
    end; 
end; 

更好的解決辦法是顛倒排序並循環前進(FirstNextEOF)。

+0

你可以做到這一點在代碼當然,但它不會花費太多在sql – tmutton

2

在MS SQL Server

select 
    t1.id, 
    t1.year, 
    t1.amount, 
    coalesce((select amount from table_1 t2 where t2.year = t1.year + 1), 0) as nextyearamount 
from 
    table_1 t1 
order by 
    t1.year 

id   year  amount  nextyearamount 
----------- ----------- ----------- -------------- 
1   2010  100   200 
1   2011  200   150 
1   2012  150   300 
1   2013  300   0 

,所以我希望它什麼v以下的作品。類似於SQLite的工作。它是否在BDE中起作用是另一回事 - 我記得它在除了簡單的SELECT之外的任何事情都相當悲慘。試試看看。

順便說一句,這是一個設計選擇問題,你爲最新的第四年專欄nextyearamount做了什麼 - 我將它設置爲零。當然,如果2014年的數量是2013年的話,那隻會是2013年的500。

如果你寧願做它的代碼,而不是SQL語句,你使用的TClientdataSet或支持fkInternalCalc字段(爲NextYearAmount一個),其他數據集類型,你可以做這樣的:

procedure TForm1.FormCreate(Sender: TObject); 
var 
    NextYearAmount : Variant; 
begin 
    VarClear(NextYearAmount); 
    CDS1.Open; // NB must be ordered by the Year field 
    CDS1.Last; 
    while not CDS1.Bof do begin 
    if NextYearAmount <> UnAssigned then begin 
     CDS1.Edit; 
     CDS1.FieldByName('NextYearAmount').Value := NextYearAmount; 
     CDS1.Post; 
    end; 
    NextYearAmount := CDS1.FieldByName('Amount').Value; 
    CDS1.Prior; 
    end; 
end; 
+0

這是否回答你的問題? – MartynA

相關問題