如何计算 2 行多个场景之间的天数

How to count days between 2 rows multiple scenarios

我想像这样计算从 table 开始的天数:

[]]1

我有 2 列状态和日期,我需要计算一行状态为 1 和 3 的天数,例如:第一行状态为 1 第二行状态为 2 这两行之间的区别是3天,同样是八九排。我需要在 sql.

中进行所有这些计算

如果您有可用的分析(又名 window)函数 (Oracle, SQL Server, Postgresql, MySQL),则可以这样做。基本思想是(使用 Oracle SQL 方言):

select
sum(trunc(next_date) - trunc(dat))
from (
select 
  status,
  dat,
  lead(dat) over (order by dat asc) next_date
from
      (  -- This is a "fake" data table
      select 1 as status, to_date('15/2/2018' ,'dd/mm/yyyy') dat from dual
      union all
      select 2 as status, to_date('18/2/2018' ,'dd/mm/yyyy') dat from dual
      union all
      select 3 as status, to_date('20/2/2018' ,'dd/mm/yyyy') dat from dual
      union all
      select 2 as status, to_date('23/2/2018' ,'dd/mm/yyyy') dat from dual
      union all
      select 4 as status, to_date('24/2/2018' ,'dd/mm/yyyy') dat from dual
      union all
      select 7 as status, to_date('27/2/2018' ,'dd/mm/yyyy') dat from dual
      union all
      select 9 as status, to_date('28/2/2018' ,'dd/mm/yyyy') dat from dual
      union all
      select 3 as status, to_date('1/3/2018' ,'dd/mm/yyyy') dat from dual
      union all
      select 14 as status, to_date('4/3/2018' ,'dd/mm/yyyy') dat from dual
      union all
      select 15 as status, to_date('7/3/2018' ,'dd/mm/yyyy') dat from dual
      union all
      select 1 as status, to_date('10/3/2018' ,'dd/mm/yyyy') dat from dual
      union all
      select 2 as status, to_date('14/3/2018' ,'dd/mm/yyyy') dat from dual
      ) d
  ) d2
where
  status in (1, 3);

其他方言可能略有不同,但思路是一样的。

这将适用于 sql-server 2012。我找不到任何可以阻止这种语法的文档。

DECLARE @t table(Status int, Date datetime)
INSERT @t
VALUES
(1,'2018-02-15'),
(2,'2018-02-18'),
(3,'2018-02-20'),
(2,'2018-02-23')

;WITH CTE as
(
  SELECT Date, lead(Date)over(order by date) NextDate, Status
  FROM @t
)
SELECT sum(DateDiff(day, Date, NextDate))
FROM CTE
WHERE Status in (1,3)