我有一个帐户,其中的利息与每个帐户相对应,如下所示
amount Date
2 01-01-2012
5 02-01-2012
2 05-01-2012
1 07-01-2012
如果帐户中的总信用额为8,则需要查询以查找信用额度可以调整的日期。
此处查询应将输出提供为02-01-2012(2 + 5< 8)。我知道这可以通过游标来处理。但是有没有方法可以在ORACLE中将其写为单个查询。
答案 0 :(得分:3)
SELECT pdate
FROM (
SELECT t.*,
LAG(date) OVER (ORDER BY date) AS pdate
8 - SUM(amount) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS diff
FROM mytable t
ORDER BY
date
)
WHERE diff < 0
AND rownum = 1
答案 1 :(得分:1)
不知道你桌子的结构,这是一个猜测:
SELECT date from your_table
GROUP BY AMOUNT
HAVING SUM(AMOUNT) < 8
注意:这少于8个。适当地更改条件。
答案 2 :(得分:0)
不做(2 + 5)&lt; 8件事:
select max(cum_sum), max(date)
from (
select date,
sum(amount) over (order by date) cum_sum
) where cum_sum < 8