简体   繁体   English

SQL计算中间天

[英]SQL calculate intermediate days

suppose I have the following table and I am looking to extract the number of days between each positive and negative movement. 假设我有下表,并且我希望提取每个正向和负向运动之间的天数。 In this way, then for each 'id' I have to calculate the intermediate days between each pair of dates and the proportion of the negative movement over the positive one, en SQL Teradata. 这样,对于每个“ id”,我必须计算每个日期对之间的中间天数以及负数在正数之间的比例,即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

You want something like this: 您想要这样的东西:

 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

I think that teradata returns a date difference as a number of days in integer format. 我认为,teradata返回的日期差为天数,为整数格式。 If it is a dateTime, you may need to case the datetime values to dates before subtracting. 如果是dateTime,则可能需要将datetime值的大小写区分为日期,然后再减去。

How about using a self join in a slightly different way, however it wil still produce extra rows since the join will be done with each row.. you can further restrict it based on your criteria 如何以略有不同的方式使用自我联接,但是由于将对每一行进行联接,因此仍然会产生额外的行。.您可以根据自己的条件进一步限制它

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)

To get the previous positive value you can use last_value : 要获取先前的正值,可以使用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

Of course, this assumes there are always alternate rows with positive & negative values. 当然,这假设总是存在具有正负值的交替行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM