Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try to avoid joining a large table

Tags:

sql

sql-server

I am using sql-server.I have a table looks like:

Name    timestamp                var1    
Bill    2015-02-05 10:10:10       x1
Bill    2015-02-05 10:10:11       x2
...
Jim     2015-02-05 10:10:10       y1
Jim     2015-02-05 10:10:11       y2
...
John    2015-02-05 10:10:10       z1
John    2015-02-05 10:10:11       z2

The table is very large say 1 million rows and the timestamp is updated every second. I want to select the people whose var1 value change delta var1 in any one minute (i.e. x61-x1 or x62-x2, etc) is between 5-7. Here is my code with joining.

declare @duration int
 set @duration = 60

    SELECT a.name,
          a.var1-b.var1 AS change
 From Table1  a
 inner join Table1 b
   on a.name = b.name
   and a.timestamp = b.timestamp +  @duration
 Where change between 5 and 7

However, I know there are two major problems.

  1. Timestamp can't be compared like this. Is there any way to fix it please?
  2. My table is too large. If joining each time, it will take too long to run. Any idea to avoid that please?
like image 980
user4441082 Avatar asked Dec 02 '25 08:12

user4441082


1 Answers

Assuming @duration is a number of minutes that join should look like

....
and a.timestamp = DATEADD(mi,@duration,b.timestamp)
....
like image 167
Jamiec Avatar answered Dec 03 '25 23:12

Jamiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!