Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I subtract values from two select statements

Tags:

sql-server

I would like to subtract one value from another value. The schema of the table is as follows:

   tag, datetime,value
   ------------
   tag1, 2010-1-1 10:10:00, 123
   tag2, 2010-2-2 10:12:00. 321

  select * from  

  ( (Select    Max(Value) as [Value1] from History WHERE Datetime ='2010-1-1 10:10'       and tagname ='tag1') as v1   -

  (  (Select    Max(Value) as [Value2] from History WHERE Datetime ='2010-1-1 10:12'      and Tagname ='tag2')  as v2))

obviously I am lost...how do I do this.

thanks

ms-sql

like image 828
fishhead Avatar asked Jan 22 '23 07:01

fishhead


2 Answers

Total guess:

select v1.Value1 - v2.Value2 from  

  (Select    Max(Value) as [Value1] from History WHERE Datetime ='2010-1-1 10:10' and tagname ='tag1') as v1   

CROSS JOIN

  (  (Select    Max(Value) as [Value2] from History WHERE Datetime ='2010-1-1 10:12'      and Tagname ='tag2')  as v2)
like image 64
Matthew Jones Avatar answered Jan 29 '23 01:01

Matthew Jones


Do you really need wrapping select statement?

You can declare two variables @value1 and @value2 and substruct them.

declare @value1 int, @value2 int

select @value1 = Max(Value) as [Value1] from History WHERE Datetime ='2010-1-1 10:10'       and tagname ='tag1'

select @value2 = Max(Value) as [Value2] from History WHERE Datetime ='2010-1-1 10:12'      and Tagname ='tag2'

select @value1 - @value2
like image 31
Andrew Bezzub Avatar answered Jan 29 '23 03:01

Andrew Bezzub