I have two tables:
t1(date d, name c(20), debit n(7), credit n(7))t2(date d, name c(20), type c(25), obal n(7))
Here’s the sample data.
T1:
DATE NAME DEBIT CREDIT
01.01.12 dad 5000
01.01.12 mum 6000
05.01.12 school 1000
01.02.12 dad 5000
01.02.12 mum 6000
10.02.12 tuition 300
10.02.12 snacks 100
01.03.12 dad 5000
01.03.12 mum 6000
01.03.12 books 500
02.03.12 rice 500
02.03.12 vegetables 900
03.03.12 snacks 100
01.04.12 dad 5000
01.04.12 mum 6000
01.04.12 meat 200
21.04.12 guest 800
T2:
DATE NAME TYPE OBAL
01.01.12 dr fee medical 8000
01.01.12 medicine medical -10000
01.01.12 dad income 400000
01.01.12 mum income 450000
05.01.12 school education 0
10.02.12 tuition education 0
10.02.12 snacks misc 0
01.03.12 books education 0
02.03.12 rice food 0
02.03.12 vegetables food 0
01.04.12 meat food 0
21.04.12 guest misc 0
Sum of (obal + credit – debit) for each name grouped by type (t2) is expected. Query used and output obtained is:
SELECT
t2.type, obal + SUM(NVL(credit - debit, 0)) as bal
FROM t2
LEFT JOIN t1 ON t2.name = t1.name
GROUP BY
t2.type, t2.obal
Results:
TYPE BAL
education -1800
food -1600
income 420000
income 474000
medical -10000
medical 8000
misc -1000
My question is: why should the type income and medical comes twice in the query output in spite of GROUP BY clause being used? I’ve tried adding DISTINCT clause before the column t2.type and that too produces the same output! One thing I could observe is that the two records of type medical in table t2 has no records in t1 matching the same name and two records of type income has a non-zero obal in t2. Please help me to overcome this problem.
The problem is that you’re not grouping just by
type, but also byobal.Try: