I'm facing a logic issue with my Query.
I have two tables Table1
and Table2
, where Table1
consists of:
value
to be summedId
to be grouped byCode
holds foreign-key toTable2
And Table2
consists of
Code
Des
the text description of code
What I'm trying to do is, group by Table1.Id
, full join on Table2.Code
, but, for each resulting group, I want to show all the rows from Table2 for each group generated by the query.
Sample code:
SELECT
Table2.Code, Table1.Id, Table2.DES,
SUM(Table1.Value) AS SUM_VAL
FROM
(
SELECT 'A' AS Code, 1 AS Id, 10 AS Value FROM DUAL UNION
SELECT 'A' AS Code, 2 AS Id, 20 AS Value FROM DUAL UNION
SELECT 'B' AS Code, 1 AS Id, 10 AS Value FROM DUAL UNION
SELECT 'B' AS Code, 1 AS Id, 30 AS Value FROM DUAL UNION
SELECT 'B' AS Code, 2 AS Id, 50 AS Value FROM DUAL UNION
SELECT 'C' AS Code, 1 AS Id, 40 AS Value FROM DUAL UNION
SELECT 'C' AS Code, 2 AS Id, 60 AS Value FROM DUAL UNION
SELECT 'D' AS Code, 1 AS Id, 20 AS Value FROM DUAL
) Table1
FULL JOIN
(
SELECT 'A' AS Code, 'This is A' AS DES FROM DUAL UNION
SELECT 'B' AS Code, 'This is B' AS DES FROM DUAL UNION
SELECT 'C' AS Code, 'This is C' AS DES FROM DUAL UNION
SELECT 'D' AS Code, 'This is D' AS DES FROM DUAL
) Table2
ON Table1.Code = Table2.Code
GROUP BY
Table2.Code, Table1.Id, Table2.DES
ORDER BY
Table2.Code, Table1.Id ASC
Result:
A 1 This is A 10
A 2 This is A 20
B 1 This is B 40
B 2 This is B 50
C 1 This is C 40
C 2 This is C 60
D 1 This is D 20
Required Result:
A 1 This is A 10
A 2 This is A 20
B 1 This is B 40
B 2 This is B 50
C 1 This is C 40
C 2 This is C 60
D 1 This is D 20
D 2 This is D 0 <- This is the target
You have somehow to show the value pair
(D,2)
eg. by making a code list with possible values and translatingNULL
to0
:UNION ALL
is used inval
because duplicates can occur.No need for
FULL OUTER JOIN
.