sdespont
sdespont

Reputation: 14025

Oracle SUM returns false summary with identicals values returing from an SELECT UNION

I am facing a problem with SUM statement.

This query returns MY_ID = 1 and QTY = 7

select my_id, sum(qty) qty
from
(     
  select 1 my_id ,2 qty from dual
union
  select 1 my_id, 5 qty from dual
)
group by my_id;

But this one returns MY_ID = 1 and QTY = 5 instead of QTY = 10.

select my_id, sum(qty) qty
from
(     
  select 1 my_id ,5 qty from dual
union
  select 1 my_id, 5 qty from dual
)
group by my_id;

How can I summary the two quantity in case of the two values are the same?

Upvotes: 1

Views: 82

Answers (3)

IsidroGH
IsidroGH

Reputation: 2037

Use union all:

select my_id, sum(qty) qty
from
(     
  select 1 my_id ,5 qty from dual
union all
  select 1 my_id, 5 qty from dual
)
group by my_id;

Upvotes: 2

simon at rcl
simon at rcl

Reputation: 7344

In the second query, the two rows in the union are identical.

There are two forms of UNION: UNION ALL and UNION DISTINCT. Which one is the default varies, but it looks like you're getting a UNION DISTINCT, which since the two (1, 5) rows are the same is only returning one of them. Change it to:

select my_id, sum(qty) qty
from
(     
  select 1 my_id ,5 qty from dual
union ALL
  select 1 my_id, 5 qty from dual
)
group by my_id;

That should give you what you want: (1, 10).

EDIT: Briefly I had union DISTINCT in the query which was wrong! Now corrected....

Upvotes: 1

Pravellika
Pravellika

Reputation: 182

Try using union all: The below works:

select my_id, sum(qty) qty
from
(     
  select 1 my_id ,5 qty from dual
union all
  select 1 my_id, 5 qty from dual
)
group by my_id;

this is because 5 union 5 is always 5. if you do union all it includes everything irrespective of it being the same!

Upvotes: 2

Related Questions