SQL计算中间天

时间:2019-01-07 18:32:23

标签: sql teradata between days

假设我有下表,并且我希望提取每个正向和负向运动之间的天数。 这样,对于SQL中的每个“ id”,我必须计算两对日期之间的中间天数以及负数在正数之间的比例。

$ portping() { python <<<"import socket; socket.setdefaulttimeout(1); socket.socket().connect(('$1', $2))" 2> /dev/null && echo OPEN || echo CLOSED; }
$ portping localhost 6006
OPEN
$ portping hostname.domain.tld 6006
CLOSED

3 个答案:

答案 0 :(得分:1)

您想要这样的东西:

 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返回的日期差为天数,为整数格式。如果它是dateTime,则可能需要将datetime值设置为日期后再减去。

答案 1 :(得分:1)

如何以一种略有不同的方式使用自连接,但是由于将对每一行进行连接,因此它仍会产生额外的行。您可以根据自己的条件进一步限制它

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)

答案 2 :(得分: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

当然,这假定总是存在具有正负值的交替行。