基于日期的数据聚合

时间:2012-07-22 20:32:10

标签: database aggregate-functions visual-foxpro

我有一张这样的桌子(ldate d,amt n(7),rdate d)。字段是贷款日期,金额,发布日期。

此处,记录被视为待处理,具有空的发布日期。例如,

SELECT SUM(AMT) FROM TABLE WHERE RDATE = {}

给出直至日期的净待定金额

在计算给定日期的待处理金额时,如果记录的发布日期为空,或者该记录的发布时间晚于给定日期,则该记录将被视为待处理!因此,要在{2011-10-09}上计算待处理金额,查询为:

SELECT SUM(AMT) FROM TABLE WHERE LDATE <= {2011-10-09} AND (RDATE > {2011-10-09} OR RDATE = {})

现在,我如何从上表中逐年计算待定金额?我期望的结果是这样的:

Year    PendingAmt 
2009    1,15,000 
2010    1,38,000 
2011    1,71,000

注意:实际表中还有许多其他字段。为简洁起见,我在这里只提到了重要的领域。 RDBMS使用Microsoft Visual Foxpro 9.0

更新:添加了样本数据

CREATE TABLE VB(LDATE DATE, AMT NUMERIC(7), RDATE DATE);

INSERT INTO VB VALUES('2010-01-05', 12000, NULL);
INSERT INTO VB VALUES('2010-03-15', 25000, '2010-04-19');
INSERT INTO VB VALUES('2010-05-21', 31000, NULL);
INSERT INTO VB VALUES('2010-07-03', 58000, '2010-07-11');
INSERT INTO VB VALUES('2010-09-10', 47000, NULL);
INSERT INTO VB VALUES('2010-11-30', 63000, '2011-01-09');

INSERT INTO VB VALUES('2011-02-15', 21000, NULL);
INSERT INTO VB VALUES('2011-04-05', 52000, '2011-04-11');
INSERT INTO VB VALUES('2011-06-03', 13000, NULL);
INSERT INTO VB VALUES('2011-08-21', 85000, '2011-09-19');
INSERT INTO VB VALUES('2011-10-30', 74000, '2012-02-10');
INSERT INTO VB VALUES('2011-12-10', 36000, '2012-03-29');

INSERT INTO VB VALUES('2012-01-05', 15000, NULL);
INSERT INTO VB VALUES('2012-02-15', 25000, NULL);
INSERT INTO VB VALUES('2012-03-15', 35000, NULL);
INSERT INTO VB VALUES('2012-10-30', 30000, '2012-11-21');
INSERT INTO VB VALUES('2012-11-30', 31000, '2012-12-31');
INSERT INTO VB VALUES('2012-12-10', 12000, NULL);

由于

2 个答案:

答案 0 :(得分:1)

更新:基于您现在提供的数据以及其中包含的其他信息(例如,对于未付贷款,rDate不为空,但为空,这是改进的查询:

SELECT YEAR(ldate)yr,SUM(amt)pamt;   来自vb;   WHERE(rdate&gt; DATE(YEAR(ldate),12,31)或ISNULL(rdate));   GROUP BY年;   INTO CURSOR结果

我得到的结果是:

2010 153000 2011 14400 2012 87000

根据我对你的问题的理解,这是正确的。

答案 1 :(得分:0)

最简单的事情是工会:

SELECT 2009 as yr, SUM(AMT) as amount
FROM TABLE
WHERE LDATE <= {2009-12-31} AND (RDATE > {2009-12-31} OR RDATE = {})
union all
SELECT 2010 as yr, SUM(AMT) as amount
FROM TABLE
WHERE LDATE <= {2010-12-31} AND (RDATE > {2010-12-31} OR RDATE = {})
union all
SELECT 2011 as yr, SUM(AMT) as amount
FROM TABLE
WHERE LDATE <= {2011-12-31} AND (RDATE > {2011-12-31} OR RDATE = {})