tags:

views:

52

answers:

3

Hi,

I have two SQL queries I want to combine into one. The first one selects all the IDs of the rows I need to add in the second one:

SELECT t.mp_id FROM t_mp AS t
JOIN t_mp_og USING (mp_id)
WHERE og_id = 2928
AND t.description = 'Energy'

The second one should add together the values from the rows returned by the first query. Up until now I've only been able to add several selects with a + in between them. For a dynamic query that adds all the rows returned by query one, I'd like to do something equivalent to "foreach(value from query1){ sum += value }" and return that sum.

SELECT(

(SELECT current_value FROM t_value_time WHERE mp_id = 29280001 AND time_id =
(SELECT time_id FROM t_time WHERE time_stamp = 
(SELECT max(time_stamp) FROM v_value AS v WHERE time_stamp is not null AND mp_id = 29280001)))
+
(SELECT current_value FROM t_value_time WHERE mp_id = 29280015 AND time_id =
(SELECT time_id FROM t_time WHERE time_stamp = 
(SELECT max(time_stamp) FROM v_value AS v WHERE time_stamp is not null AND mp_id = 29280015)))
+
(SELECT current_value FROM t_value_time WHERE mp_id = 29280022 AND time_id =
(SELECT time_id FROM t_time WHERE time_stamp = 
(SELECT max(time_stamp) FROM v_value AS v WHERE time_stamp is not null AND mp_id = 29280022)))

);

My two problems: I don't know how to add all rows in a set, only the manual "+" way. I also don't know how to put the ID from the row into the SELECT getting the value. I've tried AS, but it seems to only work for tables, not single values.

Thanks for you help, MrB

A: 

Have you tried SELECT Name, SUM(X) FROM Table GROUP BY Name

Noel Abrahams
A: 

here is the edited query

select t.mp_id,sum(current_value)
from t_value_time t, t_time tim, v_value v
where 
where t.mp_id = v.mp_id
    and v.time_stamp is not null
    and tim.time_stamp = MAX(v.time_stamp)
    and t.time_id=tim.time_id
    and t.mp_id in ( 29280001,29280015,29280022)

group by t.mp_id

use SUM() for aggregation

Aamod Thakur
I tried that but it says "Subselect returned more than 1 row". I guess that isn't allowed in WHERE subselects?
Mr Bubbles
pl chk edited answer
Aamod Thakur
A: 

SELECT SUM(CURRENT_VALUE )

FROM

T_VALUE_TIME INNER JOIN T_TIME ON T_VALUE_TIME.TIME_ID=T_TIME.TIME_ID

JOIN V_VALUE ON T_TIME.TIME_STAMP=V_VALUE.TIME_STAMP

WHERE T_VALUE_TIME.MP_ID IN (SELECT t.mp_id FROM t_mp AS t JOIN t_mp_og USING (mp_id)

WHERE og_id = 2928

AND t.description = 'Energy' )

AND T_TIME.TIME_ID=(SELECT MAX(TIME_STAMP) FROM V_VALUE WHERE TIME_STAMP IS NOT NULL)

GROUP BY V_VALUE.MP_ID