在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;
'2010 100'是一列嗎? – tmutton
我無法理解你在問什麼:( – fantaghirocco
「2010 100」,「2011 200」在一個或兩個字段中? – tmutton