473,889 Members | 1,764 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comparing data in two consecutive rows from a single table

I'm trying to come up with an elegant, simple way to compare two
consecutive values from the same table.

For instance:

SELECT TOP 2 datavalues FROM myTable ORDER BY timestamp DESC

That gives me the two latest values. I want to test the rate of
change of these values. If the top row is a 50% increase over the row
below it, I'll execute some special logic.

What are my options? The only ways I can think of doing this are
pretty ugly. Any help is very much appreciated. Thanks!

B.
Jul 20 '05 #1
22 24683
>> SELECT TOP 2 datavalues FROM myTable ORDER BY timestamp DESC;

That gives me the two latest values. I want to test the rate of
change of these values. If the top row is a 50% increase over the row
below it, I'll execute some special logic. <<

TIMESTAMP is a reserved word in Standard SQL, which matches T-SQL
DATETIME. Rows have no physical ordering in a table, so that part
makes no sense. Or it means that you still have a mental model of a
sequential file -- probably a clipboard with a single column for data
points and a single column for a timeclock imprint.

That is not how to think about it in an RDBMS. If you have an event,
then you need to show a duration. This is Einstein's physics and
Zeno's paradoxes. Furthermore, each row must represent a complete
fact in itself, not half a fact. Let's try again:

CREATE TABLE
(start_datavalu e DECIMAL(8,4) NOT NULL,
end_datavalue DECIMAL(8,4) NOT NULL,
start_time TIMESTAMP DEFAULT CURRENT_TIMESTA MP
NOT NULL PRIMARY KEY,
end_time TIMESTAMP, -- null means still open
..
);

As each sample is taken, do an insert and an update (pardon my
Standard SQL-92):

BEGIN ATOMIC

INSERT INTO Foobar
VALUES (:datavalue, (SELECT start_time FROM Foobar WHERE end_time IS
NULL),
CURRENT_TIMESTA MP, NULL, ..);

UPDATE Foobar
SET end_time = CURRENT_TIMESTA MP
WHERE end_time IS NULL;

END;

I think the code you want is a bit more complex. A change over time
needs to consider the time involved. It is one thing for a car to go
from 0 to 60 mph in 10 seconds and quite another for it to take 10
hours. But without considering the rate of change:

SELECT start_datavalue , end_datavalue, start_time, end_time
FROM Foobar
WHERE start_value/end_time >= 0.5000
OR start_value/end_time >= 2.0000);

This shows the rows where things doubled or halved in their timeslots,
you can add (end_time-start_time) to get the duration, do other
ratios, etc.
Jul 20 '05 #2
--CELKO-- (jc*******@eart hlink.net) writes:
TIMESTAMP is a reserved word in Standard SQL, which matches T-SQL
DATETIME. Rows have no physical ordering in a table, so that part
makes no sense. Or it means that you still have a mental model of a
sequential file -- probably a clipboard with a single column for data
points and a single column for a timeclock imprint.


So why not? I bet the underlying business problem looks a whole like
that!

You know, most people who are using databases are trying to solve
real-world problems, not do exercises in relational algebra.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #3

"--CELKO--" <jc*******@eart hlink.net> wrote in message
news:18******** *************** ***@posting.goo gle.com...
SELECT TOP 2 datavalues FROM myTable ORDER BY timestamp DESC;


That gives me the two latest values. I want to test the rate of
change of these values. If the top row is a 50% increase over the row
below it, I'll execute some special logic. <<

TIMESTAMP is a reserved word in Standard SQL, which matches T-SQL
DATETIME. Rows have no physical ordering in a table, so that part
makes no sense. Or it means that you still have a mental model of a
sequential file -- probably a clipboard with a single column for data
points and a single column for a timeclock imprint.

That is not how to think about it in an RDBMS. If you have an event,
then you need to show a duration. This is Einstein's physics and
Zeno's paradoxes. Furthermore, each row must represent a complete
fact in itself, not half a fact. Let's try again:


I have to disagree here Joe.

For example, one of our tables records the time a banner ad is served.
There's no "begin and end" there's an instant.

Jul 20 '05 #4
IF EXISTS(
SELECT TOP 1
datavalues as firstdatavalue,
(SELECT TOP 1
datavalues
FROM myTable AS myTable2
WHERE myTable2.timest amp < myTable.timesta mp
ORDER BY timestamp DESC
) AS nextdatavalue
FROM myTable
ORDER BY timestamp DESC
)
BEGIN
-- ** Do My special Logic
END

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #5
Here's one that only needs to do one table scan...

IF
(SELECT
MAX(Top2.datava lues) / MIN(Top2.datava lues)
FROM
(SELECT
TOP 2 datavalues
FROM
myTable
ORDER BY timestamp DESC) AS Top2
) >= 2
BEGIN
...blah blah blah...
END

"Bryan Guilliams" <br************ @hotmail.com> wrote in message
news:3d******** *************** ***@posting.goo gle.com...
I'm trying to come up with an elegant, simple way to compare two
consecutive values from the same table.

For instance:

SELECT TOP 2 datavalues FROM myTable ORDER BY timestamp DESC

That gives me the two latest values. I want to test the rate of
change of these values. If the top row is a 50% increase over the row
below it, I'll execute some special logic.

What are my options? The only ways I can think of doing this are
pretty ugly. Any help is very much appreciated. Thanks!

B.

Jul 20 '05 #6
On Wed, 2 Jun 2004 22:40:31 -0400, Jonathan Amend wrote:
Here's one that only needs to do one table scan...


Nice! :-)
Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #7
Hugo Kornelis <hugo@pe_NO_rFa ct.in_SPAM_fo> wrote in message news:<49******* *************** **********@4ax. com>...
Hi Bryan,

IF (SELECT TOP 1 datavalues FROM myTable ORDER BY timestamp DESC) >
(SELECT TOP 1 datavalues FROM
(SELECT TOP 2 datavalues, timestamp
FROM myTable ORDER BY timestamp DESC) A
ORDER BY timestamp ASC) * 1.5
BEGIN
do something
END
Best, Hugo


Hugo, this works perfectly and is exactly what I was looking for! Thanks a ton!

B.
Jul 20 '05 #8
You're right, of course, but a few words in my defense...

jc*******@earth link.net (--CELKO--) wrote in message news:<18******* *************** ****@posting.go ogle.com>...
TIMESTAMP is a reserved word in Standard SQL, which matches T-SQL
DATETIME. Rows have no physical ordering in a table, so that part
makes no sense. Or it means that you still have a mental model of a
sequential file -- probably a clipboard with a single column for data
points and a single column for a timeclock imprint.
I changed the table and column names from the real ones out of habit.
The actual datetime column is called 'time_stamp', so no problem
there. And though rows have no physical ordering in a table, they
absolutely have a virtual ordering when you use an ORDER BY statement,
which I have.
I think the code you want is a bit more complex. A change over time
needs to consider the time involved. It is one thing for a car to go
from 0 to 60 mph in 10 seconds and quite another for it to take 10
hours. But without considering the rate of change:


Luckily, the problem is not that complex. I'm pulling data from
another source that already takes care of all of that. I can be
completely confident that the data are exactly x minutes apart and
need only act if the most recent value is significantly greater than
the previous one.

I very much appreciate the instruction and help. Everything you wrote
was very informative and I thank you!

B.
Jul 20 '05 #9
>> I have to disagree here Joe. For example, one of our tables
records the time a banner ad is served. There's no "begin and end"
there's an instant. <<

Your banner ads have no duration? Wow! That means that if I want to
run 1000 ads, and a database that records times to 1/1000 of a second,
then I can put 1000 ads in each second :)

Time intervals in SQL are shown as either (start, finish) and (start,
duration) -- look up the stuff for the OVERLAPS predicate in Standard
SQL.
Jul 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2934
by: Vorpal | last post by:
Here is a small sample of data from a table of about 500 rows (Using MSSqlserver 2000) EntryTime Speed Gross Net ------------------ ----- ----- 21:09:13.310 0 0 0 21:09:19.370 9000 NULL NULL 21:09:21.310 NULL 95 NULL 21:10:12.380 9000 NULL NULL 21:10:24.310 NULL 253 NULL
41
3982
by: Odd-R. | last post by:
I have to lists, A and B, that may, or may not be equal. If they are not identical, I want the output to be three new lists, X,Y and Z where X has all the elements that are in A, but not in B, and Y contains all the elements that are B but not in A. Z will then have the elements that are in both A and B. One way of doing this is of course to iterate throug the lists and compare each of the element, but is there a more efficient way? ...
2
4201
by: Bung | last post by:
Hi, I am not really familiar with MS ACCESS. However, I am trying to make some reports where you compare current data from a table with old data from the same table. What I'm saying is we have a database with current data, and the same database with old data. I need to create reports for new rows inserted, deleted rows, and updates rows. I'm having trouble figuring how to query which rows have been updated (meaning the primary...
0
1696
by: laxmiuk | last post by:
I've original version of a table called PMM (Product Material Master). Thro' a web interface, user can change that table contents. Once changed, i need to raise an ECN (Engineering CHange Note) specifying what changes happened to original PMM table whether rows are deleted, new rows are added or existing rows are modified etc. I've both old and new version of PMM tables. The difference between two PMM tables are captured in a third table...
17
3042
by: Justin Emlay | last post by:
I'm hopping someone can help me out on a payroll project I need to implement. To start we are dealing with payroll periods. So we are dealing with an exact 10 days (Monday - Friday, 2 weeks). I have a dataset as follows (1 week to keep it short): Employee 1 - Date 1 Employee 1 - Date 2
0
3771
by: varac | last post by:
Hi list, I am new to mysql and would appreciate any advice that you have to offer. I am attempting to batch insert 100 rows into a table, and I need to know the 100 id's of all the inserted rows. I know that I can find the id of the last inserted row despite my app being multi-threaded, since the select last inserted command is connection-specific.
2
2955
by: Beliavsky | last post by:
How can I replace multiple consecutive spaces in a file with a single character (usually a space, but maybe a comma if converting to a CSV file)? Ideally, the Python program would not compress consecutive spaces inside single or double quotes. An inelegant method is to repeatedly replace two consecutive spaces with one.
1
1593
by: Mike | last post by:
Hi All, I'm using vb.net as my codebehind lang. and the following code is being executed in my aspx.vb page to stamp a DB row. Dim oStatsInfo As New StatsInfo(CartID, Batch, Set, Num, 0, 0, 0, 1, 0, 1) Dim oStatsStamp As New Stats(_DataSource, oStatsInfo) Dim tStamp As New Threading.Thread(AddressOf oStatsStamp.StampStatsList)
3
1268
by: emeped | last post by:
I am using C#.NET 2003. Please I want to know if it is possible and how to insert the same data into 2 or more consecutive rows in a datatable column, at the same time, by a single click of a button. Data will be from a textbox bound to the column. Thanks.
0
9810
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10896
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9612
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7151
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5830
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6029
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4650
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4251
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3257
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.