CREATE TABLE PAYMENTS
(
CTRL_NO NUMBER NOT NULL,
CUSTOMER_NO NUMBER NOT NULL,
CTYPE VARCHAR2(10 BYTE) NOT NULL,
AMOUNT NUMBER,
PAYMENT_DATE DATE
)
CREATE UNIQUE INDEX TEST1_PK ON PAYMENTS
(CTRL_NO)
ALTER TABLE PAYMENTS ADD (
CONSTRAINT TEST1_PK
PRIMARY KEY
(CTRL_NO)
USING INDEX
Insert into PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(266, 272, 'CASH', -47, TO_DATE('12/09/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(286, 272, 'CASH', 47, TO_DATE('12/12/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(701, 272, 'CASH', -200, TO_DATE('12/13/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(752, 272, 'INV', -91, TO_DATE('01/11/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into .PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(307, 252, 'AUTO', -9.35, TO_DATE('12/12/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into .PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(126, 252, 'AUTO', -128, TO_DATE('12/05/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into .PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(86, 252, 'INV', -18, TO_DATE('12/05/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into .PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(5890, 400, 'CASH', 120, TO_DATE('03/07/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into .PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(5888, 400, 'CASH', 76.41, TO_DATE('03/07/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into .PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(5886, 400, 'CASH', 86.34, TO_DATE('03/07/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into .PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(5680, 400, 'CASH', 158.97, TO_DATE('03/06/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into .PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(5819, 400, 'CASH', -40.94, TO_DATE('03/06/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into .PAYMENTS
(CTRL_NO, CUSTOMER_NO, CTYPE, AMOUNT, PAYMENT_DATE)
Values
(718, 400, 'INV', -40.04, TO_DATE('12/21/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
COMMIT;
我正在尝试获取最后一次现金交易的总和(金额)。如果没有,则只需返回 0。
这是我到目前为止的查询:
select p1.customer_no, max( p1.payment_date ) ,
( select nvl(sum(p2.amount), 0)
from payments p2
where p2.ctype = 'CASH'
and p2.customer_no = p1.customer_no
) as last_payment_date
from payments p1
group by p1.customer_no
order by p1.customer_no ;
问题是 272 应该是 11-jan-12 -200,但是上面的查询返回 13-dec-11 -200。另外,我应该得到 400 7-mar-12 282.75 而不是 400.78。