在SQL中查找适合特定时间段的数据,该时间段不具体

时间:2016-07-26 15:54:00

标签: sql teradata

我正在尝试在SQL中编写一个查询,该查询将在一个时间窗口内显示数据。我需要在2014年4月30日到2016年3月31日期间(EP)结束。但是,我需要确保在周年纪念日之前有12个月的数据。这是我到目前为止所写的内容:

Select
    acct_id, eom, acct_eff_dt, anniv_dt,
    mkt_sgmt, subacct,
    case 
       when eom < cast('2015-' || substr(anniv_dt,1,2) || '-' || substr(a.anniv_dt,3,2) as date) 
          then 'yes' 
          else 'no' 
    end as before_anniv,
    cast('2015-' || substr(a.anniv_dt,1,2) || '-' || substr(a.anniv_dt,3,2) as date)-365 as before_anniv_date,
    cast('2015-' || substr(a.anniv_dt,1,2) || '-' || substr(a.anniv_dt,3,2) as date)+365 as after_anniv_date,
    sum(a.prem_rate_amt) as premium,
    sum(a.incurred_amt) as paid,
    (paid/premium) as lossratio
from 
    data
/*
inner join
    (select distinct
acct_id,
anniv_dt,
add_months(cast('2014-' || substr(anniv_dt,1,2) || '-' || substr(anniv_dt,3,2) as date),-11)-1 as before_anniv,
add_months(cast('2014-' || substr(anniv_dt,1,2) || '-' || substr(anniv_dt,3,2) as date),12)-1 as after_anniv

from data
where anniv_dt <> '    '
) b
on a.eom between before_anniv and after_anniv
*/


where 
    covrg_cd IN ('11','25','26')
    and mkt_sgmt in('NRMM','NRSG','LGC','LGL','MGC','MGL','TCF')
    and eom between '2014-05-31' and '2016-06-30'
    and prem_rate_amt <> '0'
group by 
    1,2,3,4,5,6,7,8
order by 
    1,2,3,4,5,6,7,8

1 个答案:

答案 0 :(得分:0)

如果您使用内部查询对外部查询进行分组,则可能更容易调试并确认您的日期是您所期望的:

SELECT
    covrg_cd, mkt_sgmt, eom,  prem_rate_amt,
    acct_id, acct_eff_dt, anniv_dt,
    subacct,
    a.prem_rate_amt,
    a.incurred_amt,
    paid/premium AS lossratio,
    CAST('2015-' || SUBSTR(anniv_dt,1,2) || '-' || SUBSTR(a.anniv_dt,3,2)  AS DATE) AS dt_comp
FROM 
    DATA a
WHERE 
    covrg_cd IN ('11','25','26')
    AND mkt_sgmt IN('NRMM','NRSG','LGC','LGL','MGC','MGL','TCF')
    AND eom BETWEEN '2014-05-31' AND '2016-06-30'
    AND prem_rate_amt <> '0'

然后在您的外部查询中,您可以直接引用dt_comp,而不是重新计算同一日期3次或更多次。