用于根据优先级解决重叠的SQL查询

时间:2017-06-06 18:17:57

标签: sql db2

我正在考虑编写一个查询来根据存储该行优先级的列来解决重叠日期。这有助于我决定是否需要保留该行或将其替换为其他重叠行。例如:

FromDate   ToDate    Priority
-----------------------------
1/1/2014   6/30/2014     1    --row1
2/1/2014   7/30/2014     2    --row2

我的结果应如下所示

FromDate   ToDate     Priority
------------------------------
1/1/2014   6/30/2014     1    --row 1
7/1/2014   7/30/2012     2    --row 2

1 个答案:

答案 0 :(得分:1)

with temp1 (FromDate,todate, dt, priority) as                     
(                                                                 
  SELECT FromDate,todate,fromdate as dt  ,Priority                
  FROM mytable                                                    
    UNION ALL                                                     

  SELECT FromDate,todate ,                                        
dt + 1 day as dt  ,Priority                                       
  FROM temp1                                                      
  WHERE dt < todate                                               
)                                                                 
SELECT min(dt) as fromdate, max(dt) as todate, priority           
FROM temp1 a                                                      
where priority = (select min(priority) from temp1 where dt =a.dt) 
group by priority