Teradata SQL:第一次在列

时间:2018-02-08 15:40:33

标签: sql teradata gaps-and-islands

因此,我有一个每日跟踪客户帐户的表格,并记录每个工作日的价值,例如该帐户的余额。

例如:

Acct_Nbr   Acct_Open_Date   System_Date   Balance
-------------------------------------------------
111        2017-12-01       2017-12-01    0.00
111        2017-12-01       2017-12-04    0.00
111        2017-12-01       2017-12-05    0.00
111        2017-12-01       2017-12-06    500.00
222        2017-12-01       2017-12-01    0.00
222        2017-12-01       2017-12-04    0.00
222        2017-12-01       2017-12-05    0.00
222        2017-12-01       2017-12-06    0.00
222        2017-12-01       2017-12-07    0.00
222        2017-12-01       2017-12-08    250.00

我正在尝试编写一个查询,该查询将返回Acct_Open_Date与Balance之前成为的System_Date之间的天数> 0(即账户获得资助的日期)。

我计划使用case when语句(即< = 5天,6-10天等)对存储桶中的天数进行分组,并为每个存储桶返回帐户数。

根据上表,它会返回:

Time_to_fund   Count_of_accts
-----------------------------
<=5 days       1
6-10 days      1
>10 days       0

我不完全确定如何编写一个查询,它将在每个帐户的基础上搜索每一行,直到找到Balance&gt;的值为止。 0,然后获取该行的System_Date并从中减去Acct_Open_Date给我#天。

任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

select
   CASE WHEN diff <=  5 THEN'<=5 days'
        when diff <= 10 then '6-10 days'
        ELSE '>10 days'
   END as Time_to_fund,
   COUNT(*)
from
 (
    select
       System_Date - Acct_Open_Date as diff -- number of days between
    from mytable
    where Balance > 0 
    qualify -- find the first row with a Balance > 5
       row_number()
       over (partition by Acct_Nbr
             order by System_Date) = 1
 ) as dt

答案 1 :(得分:0)

尝试在GROUP BY中使用GROUP BY:

SELECT CASE WHEN fund_times.Time_to_fund_in_days<= 5 THEN'<=5 days'
when fund_times.Time_to_fund_in_days<= 10 then '6-10 days'
ELSE '>10 days' END as Time_to_fund, COUNT(fund_times.acct_Number) AS Count_of_accts
    (SELECT t.acct_Number, MIN( (t.System_Date - t.Acct_Open_Date) * 86400) as Time_to_fund_in_days
    from table as T
    WHERE t.Balance>0
    GROUP BY t.acct_Number) AS fund_times
GROUP BY CASE WHEN fund_times.Time_to_fund_in_days<= 5 THEN'<=5 days'
when fund_times.Time_to_fund_in_days<= 10 then '6-10 days'
ELSE '>10 days' END