如果日期符合条件,请在某个日期添加一定天数

时间:2014-06-02 16:07:39

标签: sql sql-server tsql date format

我的任务是延长两个日期之间的持续时间。我在Excel中执行平均值等,所以我只提取开始和结束日期。由于我们有一个数据源没有添加结束日期,因此我将拉出最旧的行(有多个交易),其中status ='已关闭'。唯一的问题是,其中一些日期实际上是在报告日期之前。因此,添加了一些逻辑以使用会计期间,如果结束或“关闭”状态将设置为关闭。日期大于报告的日期。如果状态仍设置为“打开”,则此日期也会使用今天的日期作为结束日期。我的问题是会计日期是本月的第一天。我需要做的是更改列' end_date'的会计日期。到该月的最后一天,或该月的第28天。我搜索了如何做到这一点并找到了一些帮助,但我无法弄清楚如何在这些其他规定发挥作用时得到我需要的东西。任何帮助,将不胜感激。

摘要:我需要在' end_date'中添加27天的日期。如果他们使用会计日期而不是今天的日期(这些仅适用于来自&x; xls'数据源的记录。

这是我正在运行的查询:

SELECT product_sub.product as product       
      ,product_sub.sub_product as sub_product       
      ,fl_dtl.num_claim as num_claim    
      ,fl_dtl.data_source as data_source    
      ,fl_dtl.status as status  
      ,fl_dtl.d_reported as d_reported  
      ,CASE 
         WHEN fl_dtl.data_source = 'xls' and fl_dtl.d_reported > close_xls.d_closed     THEN fl_dtl.d_reported  
         WHEN fl_dtl.data_source = 'xls' and fl_dtl.d_reported <= close_xls.d_closed THEN close_xls.d_closed
         ELSE fl_dtl.d_closed
       END as close_date    
      ,CASE 
         WHEN fl_dtl.data_source = 'xls' and fl_dtl.d_reported > close_xls.d_closed THEN COALESCE(fl_dtl.d_reported,GETDATE())  
         WHEN fl_dtl.data_source = 'xls' and fl_dtl.d_reported <= close_xls.d_closed THEN COALESCE(close_xls.d_closed,GETDATE())    
     ELSE COALESCE(fl_dtl.d_closed,GETDATE())
   END as end_date  
from        
(select num_claim       
       ,pol_num     
   ,data_source 
       ,max(status) as status       
       ,min(d_reported) d_reported      
       ,min(d_closed) d_closed      
 from COMAPANY.dbo.fact_loss        
 group by num_claim     
         ,pol_num       
         ,data_source) fl_dtl
left outer join         

(select fp.pol_num      
       ,fp.product      
       ,fp.sub_product  
 from COMAPNY.dbo.fact_prem fp      
 inner join     
 (select pol_num        
        ,max(id_prem) id_prem       
  from COMAPNY.dbo.fact_prem        
  where amt_type = 'Premium'        
  group by pol_num) max_fp      
  ON fp.pol_num = max_fp.pol_num        
 AND fp.id_prem = max_fp.id_prem) as product_sub        
 ON fl_dtl.pol_num = product_sub.pol_num        
left outer join     

(select ln.num_claim        
       ,MIN(d_book) as d_closed     
 from COMAPNY.dbo.v_COMPANY_losses_new ln       
 where status like '%clos%'     
   and num_claim is not null        
 group by ln.num_claim) close_xls       
 ON fl_dtl.num_claim = close_xls.num_claim      

1 个答案:

答案 0 :(得分:0)

DATEADD()功能可用于在日期之间添加或减去一个时间单位。

SELECT DATEADD(unit of time, number to add, base date)
SELECT DATEADD(day,29,GETDATE())