SUM(subquery) in MYSQL
Asked Answered
C

4

30

Basically, I am trying the following:

SELECT m.col1, SUM(SELECT col5 FROM table WHERE col2 = m.col1)
FROM table AS m

This doesn't seem to work. Is there any solution?

Constrictor answered 6/1, 2012 at 11:20 Comment(1)
I had the same issue, so I solved by add extra parentheses to the subquery inside SUM.Gyratory
M
48

Why don't you do this:

SELECT m.col1, (SELECT SUM(col5) FROM table WHERE col2 = m.col1)
FROM table AS m
Multifoil answered 6/1, 2012 at 11:25 Comment(0)
B
5

yes - use joins

SELECT m.col1, SUM(j.col5) FROM table AS m 
       JOIN table AS j ON j.col2 = m.col1 GROUP BY m.col1
Bromoform answered 6/1, 2012 at 11:23 Comment(0)
N
4

Another solution is to enclose the subquery in additional parentheses

SELECT m.col1, SUM((SELECT col5 FROM table WHERE col2 = m.col1))
FROM table AS m

In my case this solved it.

Also the MySQL documentation (13.2.15 Subqueries) says:

A subquery must always appear within parentheses.

Noontime answered 5/2, 2023 at 14:44 Comment(0)
P
2

Sum is used inside the second select, where we want to sum the column. The col2 may be ambiguous column, if such column exists in the table m.

SELECT
    m.col1,
    (SELECT SUM(t.col5) FROM table AS t WHERE t.col2 = m.col1) AS sumcol
FROM table AS m
Polder answered 6/1, 2012 at 11:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.