SQL-获取下一个开始日期 - 如果结束日期是最小值,则为1天

时间:2017-04-08 16:14:11

标签: sql sql-server

最近我的桌子

有问题
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

当我创建一个视图时,我希望EndDate值为" 1753-01-01"仍然有下一个StartDate值为' Next 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)

我尝试使用over partition by但仍然无法弄清楚如何在这种情况下使用它。 提前谢谢。

3 个答案:

答案 0 :(得分: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;

这是一个奇怪的数据表示,有无限的"结束日期为数据中的最早日期,而不是最新

答案 1 :(得分: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

答案 2 :(得分: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