我有一张表格如下:
date name lookback_date
1995-01-31 T1 1994-10-24
1995-01-30 T1 1994-10-23
1995-01-29 T1 1994-10-22
1995-01-31 T2 1994-10-24
1995-01-30 T2 1994-10-23
1995-01-29 T2 1994-10-22
1995-01-31 T3 1994-10-24
1995-01-30 T3 1994-10-23
1995-01-29 T3 1994-10-22
等等
我需要计算每个记录的日期和lookback_date
之间的名字数量编辑:我需要一个看起来像这样的结果:
date name lookback_date cnt
1995-01-31 T1 1994-10-24 70
1995-01-30 T1 1994-10-23 69
1995-01-29 T1 1994-10-22 67
1995-01-31 T2 1994-10-24 73
1995-01-30 T2 1994-10-23 65
1995-01-29 T2 1994-10-22 63
1995-01-31 T3 1994-10-24 68
1995-01-30 T3 1994-10-23 66
1995-01-29 T3 1994-10-22 65
使用此声明
获取输入日期select date, ticker_name
,dateadd(days, -100, date) as lookback_date
from table1
答案 0 :(得分:0)
试试这个(我还没试过)
SELECT t1.date, t1.ticker_name, dateadd(days, -100, date) AS lookback_date,
(SELECT count(ticker_name) AS cnt
FROM table1
WHERE date > t1.date
AND date < dateadd(days, -100, date))
FROM table1 t1
它在SELECT子句中使用了一个子选择,但是需要进行优化。
基本上你想要使用两个相互引用的选择,一个用于进行日期范围选择,另一个用于计数。然后在FROM子句或SELECT子句中将它们连接起来。
FROM子句会更好,因为它更易读,因此更易于维护。