SQL 计算中间天数

SQL calculate intermediate days

假设我有以下 table 并且我希望提取每个正向和负向运动之间的天数。 这样,对于每个 'id' 我必须计算每对日期之间的中间天数以及负向移动与正向移动的比例,en SQL Teradata.

id   date  money
----------------
1    1-1   10
1    3-1   -5
1    9-1    8
1   10-1   -2
2    3-1   10
2    9-1  -10
2   15-1   20
2   19-1   -15


id  days_in prop
-----------------
1     2     0.5
1     1     0.25
2     6     1
2     4     0.75

你想要这样的东西:

 select A.id, B.date - A.date as "days_in", (B.money - A.money)  / (b.date - A.date) 
 as "prop"
 from
 (
    select X.id, X.date, min(NextDate.date) as "MinNextDate", X.money
    from [yourTable] X, [yourtable] NextDate
    where
    NextDate.date > X.date
    and NextDate.id = X.id
 ) A,
[YourTable] B
where
   A.id = B.id
   and B.date = A.MinNextDate

我认为 teradata returns 日期差异是整数格式的天数。如果它是日期时间,您可能需要在减法之前将日期时间值转换为日期。

如何以稍微不同的方式使用自联接,但是它仍然会产生额外的行,因为联接将对每一行进行。您可以根据您的条件进一步限制它

select a.id, (b.date-a.date) as days_in,
abs(b.money)/a.money as prop
from <table> a
inner join <table> b
on a.id=b.id
and a.date<>b.date
where (b.date-a.date)>0 and (abs(b.money)/a.money)>0
and (a.money>0 and b.money<=-1)

要获取之前的正值,您可以使用 last_value:

SELECT id
  ,datecol
  -- ratio between current negative and previous positive money
  ,Abs(Cast(money AS NUMBER)) /
   Last_Value(CASE WHEN money > 0 THEN money end IGNORE NULLS)
   Over (PARTITION BY id
         ORDER BY datecol)
  -- difference between current and previous date
  -- might need a cast to date or interval result if the datecol is a Timestamp
  ,datecol-
   Last_Value(CASE WHEN money > 0 THEN DATE_ end IGNORE NULLS)
   Over (PARTITION BY id
         ORDER BY datecol)
FROM vt AS t
-- return only rows with negative money
QUALIFY money < 0

当然,这是假设总是有正值和负值的交替行。