开发者

SQL query to calculate the difference between current and previous day's value

开发者 https://www.devze.com 2023-03-21 20:22 出处:网络
I have an Access .mdb database with a Table that looks similar to: +------开发者_Python百科---+------+--------+

I have an Access .mdb database with a Table that looks similar to:

+------开发者_Python百科---+------+--------+
|     date        | value |
+---------+------+--------+
|2011-05-04 12:00 | 45.9  |
|2011-05-05 12:00 | 21.2  |
|2011-05-06 12:00 | 32.2  |
|2011-05-07 12:00 | 30.4  |
|2011-05-08 12:00 | 40.4  |
|2011-05-09 12:00 | 19.8  |
|2011-05-10 12:00 | 29.7  |
+-------+---------+-------+

I would like to create a query that will return values that are derived from subtracting one value from a previous day value.

For example: The query would calculate (21.2-45.9) and return -24.7 (32.2-21.2) and return -11.0 (30.4-32.2) and return -1.8 etc

How can I accomplish this in a SELECT statement?


You can use a query that employs a self-join on the table in question:

SELECT 
  t.dateValue , t.singleValue - IIF(ISNULL(tNext.singleValue), 0, tNext.singleValue)
FROM 
  test t 
  LEFT JOIN test tNext
  ON t.dateValue = DateAdd("d", -1, tNext.dateValue)
WHERE 
  t.dateValue = #2011-05-08 12:00#;

Outputs

dateValue               Expr1001
----------------------  ----------------
05/08/2011 12:00:00 PM  20.6000022888184

DDL and inserts below

CREATE TABLE test (dateValue DATETIME, singleValue SINGLE);

INSERT INTO test VALUES (#2011-05-04 12:00#, 45.9);
INSERT INTO test VALUES (#2011-05-05 12:00#, 21.2);
INSERT INTO test VALUES (#2011-05-06 12:00#, 32.2);
INSERT INTO test VALUES (#2011-05-07 12:00#, 30.4);
INSERT INTO test VALUES (#2011-05-08 12:00#, 40.4);
INSERT INTO test VALUES (#2011-05-09 12:00#, 19.8);
INSERT INTO test VALUES (#2011-05-10 12:00#, 29.7);


Here's the query that worked for me:

SELECT t2.date, t2.value-t1.value
FROM Table1 AS t1, Table1 AS t2
WHERE t2.date=DATEADD("d",1,t1.date);

Thanks again, Tom H.

0

精彩评论

暂无评论...
验证码 换一张
取 消