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