我想从这样的表中计算几天:
[]] 1
我有2列状态和日期,我需要计算一行有1和3的状态的天数,例如:第一行有staus 1第二行有状态2这两行之间的差异是3天,同样的八九排。所有这些计算我都要在sql中做。
答案 0 :(得分:0)
如果您有可用的分析(aka窗口)函数(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);
其他方言可能略有不同,但想法是一样的。
答案 1 :(得分:0)
这适用于sql-server 2012.我无法找到任何会阻止此语法的文档。
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.js"></script>
<input type="date" onChange="getDate();" id="oldDate" />
<input type="date" id="newDate" />