Domanda

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?

È stato utile?

Soluzione

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;

Altri suggerimenti

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!

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....

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top