Skip to content
Advertisement

Sum value is too big when adding a another table ORACLE SQL

When I want to sum two values from two different tables – the tickets sold out on match and the TV transmission i got too big sum value in result. I figured out that for single match transmission cost is X times too big, where X is a number of tickets for this match, only when I join a tickets table. How can I repair this?

I found solution for similiar problem here: SQL: After joining tables SUM() function returns wrong value but it doesn’t work with cube.

For example sum of bilets for match of id 1 is 410.5:

is giving result 410.5 so correct. The sum for transmission is 300 000:

and it also return correct value. But when I add a ticket table I got 1200410,5 value what is incorrect:

the correct value should be 300410.5.

Advertisement

Answer

After reading your question, the following query is giving result 410.5 so correct, but the count is returning 4 (number of tickets for this match)

the second query is returning 300 000 and the count is returning 1 (only one transmission)

When you are joining the 3 tables, you have now 4 rows for the last query (transmissions) and not only 1 as expected. This is why you figured out that for single match transmission cost is X times too big, where X is a number of tickets for this match. Run the following query to validate

ID_TRANSMISSION COST
5 300000
5 300000
5 300000
5 300000

So, the solution is join the aggregations query AND not the single tables. Below an example using the SQL WITH syntax to build the subquery

If the count for the transmission query returns more than 1 (count >1), you need create also a subquery

This returns the correct value 300410.5

Then, you can add the cube syntax, I have not all tables and data to test

Hope that it can help

By the way, if you have the following error : ORA-00979: not a GROUP BY expression when running this query

this is because, you must to use the same columns used in group by cube in the SELECT. Because you are doing NVL with a SELECT expression, take care with the WHERE clause inside the NVL expression

and not

Even if l.id = m.id_league You are doing group by cube(d.id, s.id, l.id);

In your case, I suggest to modify the GROUP BY and keep the SELECT :

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement