表结构及内容如下:
数量 日期 是否结算
1023.00 2013-12-9 N
1998.00 2013-12-8 N
1999.00 2013-12-7 Y
2525.00 2013-12-6 N
2397.00 2013-12-5 N
查询2013-12-9这个日期及其之前的日期,是否结算字段是N则累加数量(碰到Y则停止累加),如上数据的计算过程应该是:
1023.00
1998.00 +
------------
3021.00
------解决方案--------------------
我排序了下时间,写了一个,坐等高手解答
WITH t AS
(SELECT 1023 mt,DATE '2013-12-9' dat,'n' flag FROM dual
UNION ALL
SELECT 1998 mt,DATE '2013-12-8' dat,'n' flag FROM dual
UNION ALL
SELECT 1999 mt,DATE '2013-12-7' dat,'y' flag FROM dual
UNION ALL
SELECT 2525 mt,DATE '2013-12-6' dat,'n' flag FROM dual
UNION ALL
SELECT 1999 mt,DATE '2013-12-4' dat,'y' flag FROM dual
UNION ALL
SELECT 2397 mt,DATE '2013-12-5' dat,'n' flag FROM dual
),
a AS (SELECT mt,dat,flag,ROWNUM rn FROM t WHERE t.dat <=DATE'2013-12-9' AND t.flag = 'y' ORDER BY dat DESC)
SELECT SUM(T.MT)
FROM T, A
WHERE T.DAT <= DATE '2013-12-9'
AND T.DAT > A.DAT
AND A.RN = 1
ORDER BY T.DAT DESC;