[英]SQL calculate intermediate days
假設我有下表,並且我希望提取每個正向和負向運動之間的天數。 這樣,對於每個“ 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
您想要這樣的東西:
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值的大小寫區分為日期,然后再減去。
如何以略有不同的方式使用自我聯接,但是由於將對每一行進行聯接,因此仍然會產生額外的行。.您可以根據自己的條件進一步限制它
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
當然,這假設總是存在具有正負值的交替行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.