2017-06-06 56 views
0

我正在查看編寫查詢來解決基於存儲該行優先級的列的重疊日期時間段。這有助於我決定是否需要保留該行或將其替換爲其他重疊行。對於e.g:SQL查詢根據優先級解決重疊問題

 
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 
+0

2012年是一個錯字,對吧? – SqlZim

+2

什麼是您的RDBMS?如果sql server 2012+你嘗試過'LAG'嗎? –

+2

[xkcd PSA ISO 8601](https://xkcd.com/1179/) – SqlZim

回答

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