而PLSQL中的循环计数器

时间:2015-06-26 18:53:55

标签: sql loops plsql while-loop

我正在编写一段plsql代码并遇到了问题。

我要做的是计算最近一个数字和前一个数字不相等的列中的实例数,然后循环。例如,

4
3
2
1
1
1
0
0
0

将返回3,因为4在三个间隔中减少为1。

4
4
3
2
1 
0 
0

将返回0,因为4在最近的时间间隔内没有减少。

到目前为止,我已写过

declare
   Counter BINARY_INTEGER :=1;
BEGIN
   while (select YTDOVERDRAFTS from (select YTDOVERDRAFTS
                 from WH_ACCTDEPOSIT
                 where ACCTNBR = xxxxxxxxxx
                 order by effdate desc)) <>
         (select Previous_YTDOVERDRAFTS from (select LAG(YTDOVERDRAFTS,1,0) 
OVER (ORDER BY EFFDATE asc) As Previous_YTDOVERDRAFTS
                 from WH_ACCTDEPOSIT
                 where ACCTNBR = xxxxxxxxxx
                 order by effdate desc))
         Counter := Counter + 1;
   END LOOP;
END;
/

这给了我这个错误

http://imgur.com/WXjXMXG.jpg

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这是如何编写自联接的。现在把它放在sql中,这样你就可以玩它了:

select min(rnb) from (
select * from (
    select YTDOVERDRAFTS, acctnbr acctnbra, effdate, row_number() over (partition by acctnbr order by effdate desc) rna
                     from WH_ACCTDEPOSIT) a
                    left join 
             (select acctnbr acctnbrb, Previous_YTDOVERDRAFTS, row_number() over (partition by acctnbr order by effdate desc) rnb from (select effdate, acctnbr, LAG(YTDOVERDRAFTS,1,0) 
    OVER (ORDER BY EFFDATE asc) As Previous_YTDOVERDRAFTS
                from WH_ACCTDEPOSIT
                ) x
            ) b on a.ACCTNBRa = b.ACCTNBRb and a.rna  = b.rnb        

        ) c
    where ytdoverdrafts -1 <> Previous_YTDOVERDRAFTS

SQL小提琴:http://sqlfiddle.com/#!3/cf436/4