SQL:添加不同行的所有值

时间:2010-10-06 10:00:00

标签: sql add

我想将两个SQL查询合并为一个。第一个选择我需要在第二个中添加的行的所有ID:

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

第二个应该将第一个查询返回的行中的值相加。到目前为止,我只能在它们之间添加一些带有+的选择。对于添加查询1返回的所有行的动态查询,我想做一些等同于“foreach(来自query1的值){sum + = value}”并返回该总和的内容。

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)))

);

我的两个问题:我不知道如何在一组中添加所有行,只有手动“+”方式。我也不知道如何将行中的ID放入SELECT中获取值。我试过AS,但它似乎只适用于表,而不是单个值。

谢谢你的帮助, MRB

3 个答案:

答案 0 :(得分:1)

这是已编辑的查询

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

使用SUM()进行聚合

答案 1 :(得分:0)

您是否尝试过SELECT Name, SUM(X) FROM Table GROUP BY Name

答案 2 :(得分:0)

SELECT SUM(CURRENT_VALUE)

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

加入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 ='能量')

AND T_TIME.TIME_ID =(SELECT MAX(TIME_STAMP)FROM V_VALUE WHERE TIME_STAMP不为空)

GROUP BY V_VALUE.MP_ID