2
SELECT SUM(SELECT type.value
FROM type,item_type 
WHERE item_type.type_id = type.id AND item_type.type_id IN (4,7)
GROUP BY type.id)

What's wrong with this query? I would like to sum all rows coming from the internal query.

richardaum
  • 6,651
  • 12
  • 48
  • 64

3 Answers3

4

You can't use SUM() function with subquerys. According to the manual the SUM() function returns the total sum of a numeric column. The way you were doing, was something like that: SELECT 1+50+30+10. Where is the table you were selecting the values? The sintax is:

SELECT SUM(column) FROM table 

Take a look at: http://www.w3schools.com/sql/sql_func_sum.asp

The correct way is

SELECT t.id, SUM(t.value)
FROM type as t,
INNER JOIN item_type as it
ON it.type_id = t.id
WHERE it.type_id IN (4,7)
GROUP BY t.id

Consider to use JOIN sintax instead of multiple tables: SQL left join vs multiple tables on FROM line?

Community
  • 1
  • 1
Marcelo Machado
  • 1,179
  • 2
  • 13
  • 33
1

You should learn to use proper join syntax and table aliases:

SELECT SUM(t.value)
FROM type t JOIN
     item_type it
     ON it.type_id = t.id 
WHERE it.type_id IN (4,7);

If you want one row for each type.id, then you need a GROUP BY.

Your query doesn't work because subqueries are not allowed as arguments to aggregation functions. Even if they were, the context would be for a scalar subquery and your subquery is likely to return more than one row.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • It should work, but GROUP BY is avoiding repeated values in `id` column. At the same time I would like to display the sum from all distinct ids in one row. – richardaum Sep 10 '15 at 21:43
0

Just use SUM without internal query :

SELECT type.id, SUM(type.value)
FROM type,item_type 
WHERE item_type.type_id = type.id AND item_type.type_id IN (4,7)
GROUP BY type.id
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116