2017-04-08 24 views
0

最近有問題,在我的表是SQL-獲得下一個起始日期 - 3天,如果結束日期是最小值

Item | Price | StartDate | EndDate 
A | 50 | 2015-01-01 | 2015-01-15 
A | 60 | 2015-01-16 | 2015-02-07 
A | 40 | 2015-02-08 | 1753-01-01 
A | 45 | 2015-02-20 | 2015-03-10 
A | 50 | 2015-03-11 | 1753-01-01 

,當我創建一個視圖,我想用「1753-01-的結束日期值01「,其仍然具有下一個StartDate值爲'下一個StartDate值-1天' 並且對於具有'1753-01-01'的EndDate值,其在沒有任何數據之後將其轉換爲今天日期

最終視圖將爲

Item | Price | StartDate | EndDate 
A | 50 | 2015-01-01 | 2015-01-15 
A | 60 | 2015-01-16 | 2015-02-07 
A | 40 | 2015-02-08 | 2015-02-19 (get next start date - 1 day) 
A | 45 | 2015-02-20 | 2015-03-10 
A | 50 | 2015-03-11 | 2017-04-08 (today date) 

我已嘗試使用分區,但仍然無法弄清楚如何在這種情況下使用它。 在此先感謝。

回答

1

您可以使用lead()

select . . ., -- the other columns you want 
     (case when enddate = '1753-01-01' and next_startdate is null 
      then cast(getdate() as date) 
      when enddate = '1753-01-01' 
      then dateadd(day, -1, next_startdate) 
      else enddate 
     end) as enddate 
from (select t.*, 
      lead(startdate) over (partition by item order by startdate) as next_startdate 
     from t 
    ) t; 

它是具有「無限」結束日期作爲數據最早日期,而不是最新一個奇怪的數據表示。

0
CREATE TABLE #test 
(
    Item varchar(50), 
    Price money, 
    StartDate date, 
    EndDate date 
) 

INSERT INTO #test VALUES 
('A', 50, '2015-01-01', '2015-01-15'), 
('A', 60, '2015-01-16', '2015-02-07'), 
('A', 40, '2015-02-08', '1753-01-01'), 
('A', 45, '2015-02-20', '2015-03-10'), 
('A', 50, '2015-03-11', '1753-01-01') 

SELECT 
    Item, 
    Price, 
    StartDate, 
    CASE 
     WHEN EndDate = '1753-01-01' AND LEAD(StartDate, 1) OVER (ORDER BY StartDate) IS NOT NULL 
      THEN DATEADD(DAY, -1, LEAD(StartDate, 1) OVER (ORDER BY StartDate)) 
     WHEN EndDate = '1753-01-01' AND LEAD(StartDate, 1) OVER (ORDER BY StartDate) IS NULL 
      THEN CAST(GETDATE() AS date) 
     ELSE EndDate 
     END AS 'EndDate' 
FROM 
    #test 

DROP TABLE #test 
0

js fiddle

試試這個

Select a.item,a.price,a.startdate, 
dateadd(day, -1,min(isnull(b.startdate,getdate()))) 
    as enddate 
from 
test a 
Left join test b on 
a.startdate < b.startdate 
Group by a.item,a.price,a.startdate 
相關問題