-1

How i can sum this selects? I need sum t.value from one select and t.value from other

select t.value as OneValues, t.clock as time
from hosts h, items i, history_uint t 
where i.hostid=h.hostid and t.itemid=i.itemid and i.hostid='223344'   and t.itemid = '0223344'
select t.value as SecondValues, t.clock as time 
from hosts h, items i,history_uint t
where i.hostid=h.hostid and t.itemid=i.itemid and i.hostid='112233' and t.itemid = '0112233'
1
  • 3
    Tip of today: Switch to modern, explicit JOIN syntax. Easier to write (without errors), easier to read (and maintain), and easier to convert to outer join if needed.
    – jarlh
    Apr 1, 2020 at 8:12

3 Answers 3

0

You can try this below logic-

SELECT i.hostid,t.itemid,t.value as OneValues, t.clock as time
FROM hosts h 
INNER JOIN items i 
    ON i.hostid=h.hostid
    AND i.hostid IN ('223344','112233')
    AND i.itemid IN ('0223344','0112233')
INNER JOIN  history_uint t 
    ON t.itemid=i.itemid
0

Use Sum aggregate function with case statement as below, if you want sum of those t.value based on t.clock then do group by on that column so that you will get clock while sum of values.

select sum(case when  i.hostid='223344'   and t.itemid = '0223344' then t.value end) as FirstValue,sum(case when  i.hostid='112233' and t.itemid = '0112233' then t.value end) as SecondValue
from hosts h, items i,history_uint t
where i.hostid=h.hostid and t.itemid=i.itemid

If it is based on t.clock then

   select t.clock, sum(case when  i.hostid='223344'   and t.itemid = '0223344' then t.value end) as FirstValue,sum(case when  i.hostid='112233' and t.itemid = '0112233' then t.value end) as SecondValue
    from hosts h, items i,history_uint t
    where i.hostid=h.hostid and t.itemid=i.itemid
    group by t.clock
0

You want conditional aggregation:

select sum(case when i.hostid = '223344' and t.itemid = '0223344' then t.value end) as value_1,
       sum(case when i.hostid = '112233' and t.itemid = '0112233' then t.value end) as value_1,

from hosts h join
     items i
     on i.hostid = h.hostid join
     history_uint t
     on t.itemid = i.itemid ;

You can repeat the conditions in a where clause if you have lots of data.

where (i.hostid = '223344' and t.itemid = '0223344') or
      (i.hostid = '112233' and t.itemid = '0112233')

Very import: Never use commas in the FROM clause. Always use proper, explicit, standard, readable JOIN syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.