這是不錯的辦法,但它是你想要什麼:
declare @a table(mDate Date, MTime int, ACCCT int, Atm nVarChar(2), AC nVarChar(1), AMT int, Location nVarChar(50))
insert into @a(mDate, MTime, ACCCT, Atm, AC, AMT, Location)
select N'7/11/16', 1040, 5555, '', 'C', 0, 'DUNKIN #3'
union all
select N'7/11/16', 1105, 5555, '#1', 'W', -20, ''
union all
select N'7/11/16', 1105, 5555, '', 'С', 0, 'ATM'
union all
select N'7/11/16', 1105, 5555, '', 'С', 0, 'DUNKIN #3'
union all
select N'7/12/16', 2141, 5555, '', 'С', 0, 'BP#9'
union all
select N'7/19/16', 1025, 5555, '#2', 'W', -40, ''
union all
select N'7/19/16', 1025, 5555, '', 'C', 0, 'ATM'
union all
select N'7/19/16', 1025, 5555, '', 'C', 0, 'SBUCKS #1'
union all
select N'7/21/16', 2102, 5555, '', 'C', 0, ''
declare @b table(mDate Date, MTime int, ACCCT int, Atm nVarChar(2), AC nVarChar(1), AMT int, mTran nVarChar(50), Location nVarChar(50))
declare @mDate Date, @MTime int, @ACCCT int, @Atm nVarChar(2), @AC nVarChar(1), @AMT int, @Location nVarChar(50)
declare @mDate2 Date, @MTime2 int, @ACCCT2 int, @Atm2 nVarChar(2), @AC2 nVarChar(1), @AMT2 int, @mTran2 nVarChar(50), @Location2 nVarChar(50)
declare @Fl int set @Fl = 0
DECLARE @Cur as CURSOR;
set @Cur = CURSOR FORWARD_ONLY FOR
select mDate, MTime, ACCCT, Atm, AC, AMT, Location
from @a
order by mDate, MTime, AMT;
OPEN @Cur
FETCH NEXT FROM @Cur INTO @mDate, @MTime, @ACCCT, @Atm, @AC, @AMT, @Location
WHILE @@FETCH_STATUS = 0
BEGIN
if @Fl = 2 set @mTran2 = @Location
if @Fl = 1
begin
set @Location2 = @Location
insert into @b (mDate, MTime, ACCCT, Atm, AC, AMT, mTran, Location)
select @mDate2, @MTime2, @ACCCT2, @Atm2, @AC2, @AMT2, @mTran2, @Location2
end
if @Fl = 2
set @Fl = 1
else if @Fl = 1 set @Fl = 0
if @AC = 'W'
begin
set @Fl = 2
set @mDate2 = @mDate
set @MTime2 = @MTime
set @ACCCT2 = @ACCCT
set @Atm2 = @Atm
set @AC2 = @AC
set @AMT2 = @AMT
end
FETCH NEXT FROM @Cur INTO @mDate, @MTime, @ACCCT, @Atm, @AC, @AMT, @Location
END
CLOSE @Cur;
DEALLOCATE @Cur;
select * from @b
首先,也是最重要的..你需要按行邏輯和使用一套基於邏輯走出一排。把B看作你的選擇語句而不是寫作。你需要的是一個自我加入表A. – xenapan
是的,這是有道理的。我會嘗試的!謝謝 – Sky
使用窗口函數'over ... order by(date)'爲你的「下兩行」。 – ajeh