3
Select sum(num) as num, sum(numbr) as numbr
from
(
    (Select 0 as num)
    union all
    (Select 1 as num)
) t, 
(
    (Select 2 as numbr)
    union all
    (Select 3 as numbr)
) t1

giving result:

num numbr
2   10

But the correct result should be

num numbr
1   5
3
  • if you use union the name of the column doesn't matter it's the order Commented Jun 9, 2016 at 6:47
  • The query is working as expected. There is a CROSS JOIN there, so rows from each table as duplicated. What exactly do you want to achieve? Commented Jun 9, 2016 at 6:50
  • @Giorgos I am not aware that the Cross Join is happening in it.. Thanks for telling... Commented Jun 9, 2016 at 6:56

4 Answers 4

2

You are doing the cross product of a table containing 0 and 1, and a table containing 2 and 3. Try removing the sums:

Select num, numbr as numbr from 
(
(Select 0 as num)
union all
(Select 1 as num))t, 
((Select 2 as numbr)
union all
(Select 3 as numbr)
)t1

This gives you:

0;2
0;3
1;2
1;3

Which will correctly sum to 2 and 10.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @small_duck
1

That happens because you are CROSS JOINING , every record connect to every record with out a relation condition, which means that in this case, your join becomes this:

NUM | NUMBR
 0      2
 0      3
 1      2  
 1      3

Which SUM(NUM) = 2 and SUM(NUMBR) = 10 .

When joining, you have to specify the relation condition unless this is what you want.

Note: You are using implicit join syntax(comma separated) , you should avoid that and use the explicit syntax and this will help you make sure you are using a relation condition (by the ON clause):

Select sum(num) as num, sum(numbr) as numbr
from
(
    (Select 0 as num)
    union all
    (Select 1 as num)
) t
INNER JOIN 
(
    (Select 2 as numbr)
    union all
    (Select 3 as numbr)
) t1
ON(t.<Col> = t1.<Col1>)

Comments

1
Select num, numbr as numbr
from
(
    (Select 0 as num)
    union all
    (Select 1 as num)
) t, 
(
    (Select 2 as numbr)
    union all
    (Select 3 as numbr)
) t1

Gives you the cartessian product of tables.

| Num | Number |
|-----|--------|
| 0   | 2      |
| 0   | 3      |
| 1   | 2      |
| 1   | 3      |

Therefore the sum of these are 2 and 10

Comments

1

Its correctly working as you wrote. If you want the result as you expected, try this:

Select sum(distinct num) as num, sum(distinct numbr) as numbr
from
(
(Select 0 as num)
union all
(Select 1 as num)
) t, 
(
(Select 2 as numbr)
union all
(Select 3 as numbr)
) t1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.