[英]sql calculate delta between the column value for one day and the previous day
I have a query like this: 我有这样的查询:
;WITH A AS (SELECT * FROM T1 where T1.targetDate=@inputdate),
B AS (SELECT A.*, T2.SId, T2.Type, T2.Value
FROM A
INNER JOIN T2 ON A.SId = T2.SId )
SELECT A.*, B.Type, B.Value
FROM B
My question is, instead of getting the Value
for @inputdate,
how to get the delta of Value
between @inputdate
and the previous day (DATEADD(day, -1, @inputdate ))
? 我的问题是,而不是得到的Value
为@inputdate,
如何获得的增量Value
之间@inputdate
和前一天(DATEADD(day, -1, @inputdate ))
Edited : 编辑 :
Sorry for not being clear, the 'Value' is of type int. 抱歉,不清楚,“值”的类型为int。 For example, if @inputdate = '20130708'
, the Value
for '20130708' is 30, and the 'Value' for previous day '20130707' is 20, so it should return (30 - 20) which is 10. 例如,如果@inputdate = '20130708'
,则Value
为“20130708”是30,而对于前一天的20130707'的“值”为20,所以它应返回(30 - 20),这是10。
Something like this, and assuming that Value is DATE format 像这样,并假设Value为DATE格式
;WITH A AS (SELECT * FROM T1 where T1.targetDate=@inputdate),
B AS (SELECT A.*, T2.SId, T2.Type, T2.Value
FROM A
INNER JOIN T2 on A.SId = T2.SId )
SELECT A.*, T2.Type, T2.Value, DATEDIFF(DAY, b.Value, DATEDADD(DAY, -1,@InputDate)) AS Delta
FROM B
let's say you have a stock prices table: which has the symbol, date and closing prices etc, you could use something like this: 假设您有一个股票价格表:其中包含交易品种,日期和收盘价等信息,您可以使用以下代码:
select symb, ret_dt, close, (close-(lead(close,1) over (partition by symb order by ret_dt desc,close)))as difference, (lead(close,1) over
(partition by symb order by ret_dt desc,close)) as lead
from stocks.nyse2010;
Note: here ret_dt
is the date, close is the closing price and I have added an additional lead column for representational purposes. 注意:此处ret_dt
是日期,收盘价是收盘价,为了说明目的,我添加了一个额外的潜在客户列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.