I have an Oracle SQL query with which I want to fectch totals of several amount columns and some descriptive columns. In short I want output like:
INDBDebnmbr INInvoicenmbr INOpenAmount
40 10 100
40 14 125
35 20 200
60 21 75
My Querystring:
SELECT TRIM(A.ACCOUNTNUMBER) AS INDBDebnmbr
, TRIM(A.VOUCHER) AS INinvoicenmbr
, A.DATE_ AS INinvoiceDate
, A.DUEDATE AS INinvoiceDueDate
, A.TXT AS INDescription
, A.EXCHANGECODE AS INCurrencyCode
, subq.AMOUNTMST AS INOriginalamount
, subq.SETTLEAMOUNTMST AS INpaidAmount
, subq.OPENAMOUNT AS INOpenAmount
FROM (
SELECT DEBTRANS.VOUCHER AS VOUCHER,
SUM(DEBTRANS.AMOUNTMST) AS AMOUNTMST,
SUM(DEBTRANS.SETTLEAMOUNTMST) AS SETTLEAMOUNTMST,
SUM(DEBTRANS.AMOUNTMST - DEBTRANS.SETTLEAMOUNTMST) AS OPENAMOUNT
FROM XAL_SUPERVISOR.DEBTRANS DEBTRANS
WHERE DEBTRANS.OPEN = 1
AND DEBTRANS.TRANSTYPE <> 9
AND (DEBTRANS.AMOUNTMST - DEBTRANS.SETTLEAMOUNTMST) <> 0
AND DEBTRANS.DATASET = 'FIK'
GROUP BY DEBTRANS.VOUCHER
) subq,
XAL_SUPERVISOR.DEBTRANS A
WHERE subq.VOUCHER = A.VOUCHER
GROUP BY A.VOUCHER,
A.ACCOUNTNUMBER,
A.DATE_,
A.DUEDATE,
A.TXT,
A.EXCHANGECODE,
subq.AMOUNTMST,
subq.SETTLEAMOUNTMST,
subq.OPENAMOUNT
I do however get
INDBDEBNMBR ININVOICENMBR ININVOICEDATE ININVOICEDUEDATE INOPENAMOUNT
10 2022903 12-2-2011 0:00 24-2-2011 0:00 110
35 2022903 11-2-2011 0:00 23-2-2011 0:00 110
20 2022903 17-2-2011 0:00 1-3-2011 0:00 110
10 2022903 14-2-2011 0:00 26-2-2011 0:00 110
29211 2022903 14-2-2011 0:00 26-2-2011 0:00 11
How do I get the correct SUMS by DEBTRANS.VOUCHER with the descriptive columns?
Thanks in advance,
Mike
You’re unnecessarily joining back to the table to get your additional columns. I’m guessing that the problem is that you aren’t repeating the filter conditions for the outer instance of the table.
Does this do what you want?
If not, then presumably one or more of those additional columns does not have a unique value by voucher. In this case, you need to decide how you want to select which value to display for each group. You could for example select the maximum value as shown below, but does that make sense for your businesss logic?