我想找到第二次(重复)的SQL记录,其值介于(15和19)之间,相隔90天(日期不需要连续)
ChildID Value ValuetieredDate
1 15 2015-01-01
1 16 2015-04-01
1 2 2015-05-01
2 16 2015-01-01
2 17 2015-02-01
3 15.5 2017-08-01
3 17 2017-09-07
3 18 2018-01-03
4 16 2018-01-03
4 3 2005-01-03
5 20 2012-02-01
5 16 2012-06-02
5 19 2015-09-08
我想选择CHILDID 1,3,5 我试过了
Select distinct ChildID,b.identifier,valueTieredDate,Value
,DateDiff(Day,lead(b.valueTieredDate) OVER (Partition by b.Childid order by b.valueTieredDate desc),b.valueTieredDate) as Datedif --Find consecutive dates
,DateDiff(day,First_Value(b.valueTieredDate) Over (Partition by ChildID order by b.valueTieredDate asc),valueTieredDate ) as Datedif1 --Not consecutive
where value between 15 and 19.9
group by ChildID,b.identifier,valueTieredDate,Value
having count(distinct value)>1
From TestTable
答案 0 :(得分:0)
如果我弄错了,这应该有用
with cte (ChildID, Value, ValuetieredDate) as (
select
a, b, cast(c as datetime)
from
(values (1,15,'20150101')
,(1,16,'20150401')
,(1,2,' 20150501')
,(2,16,'20150101')
,(2,17,'20150201')
,(3,15.5,'20170801')
,(3,17,'20170907')
,(3,18,'20180103')
,(4,16,'20180103')
,(4,3,' 20050103 ')
,(5,20,'20120201')
,(5,16,'20120602')
,(5,19,'20150908')) t(a, b, c)
)
select
a.ChildID
from
cte a
join cte b on a.ChildID = b.ChildID and a.ValuetieredDate < b.ValuetieredDate
where
a.value between 15 and 19.9
and b.value between 15 and 19.9
group by a.ChildID
having max(datediff(dd, a.ValuetieredDate, b.ValuetieredDate)) >= 90
编辑:只需从查询中删除GROUP BY
select
a.ChildID, a.Value, b.Value, a.ValuetieredDate, b.ValuetieredDate
from
cte a
join cte b on a.ChildID = b.ChildID and a.ValuetieredDate < b.ValuetieredDate
where
a.value between 15 and 19.9
and b.value between 15 and 19.9
and datediff(dd, a.ValuetieredDate, b.ValuetieredDate) >= 90
答案 1 :(得分:0)
with cte (ChildID, Value, ValuetieredDate) as
( select a, b, cast(c as datetime)
from (values (1,15,'20150101')
,(1,16,'20150401')
,(1,2,' 20150501')
,(2,16,'20150101')
,(2,17,'20150201')
,(3,15.5,'20170801')
,(3,17,'20170907')
,(3,18,'20180103')
,(4,16,'20180103')
,(4,3,' 20050103 ')
,(5,20,'20120201')
,(5,16,'20120602')
,(5,19,'20150908')
) t(a, b, c)
)
select distinct cte1.ChildID
from cte as cte1
join cte as cte2
on cte1.ChildID = cte2.ChildID
and cte1.Value between 15 and 19
and cte2.Value between 15 and 19
and DATEDIFF(dd, cte1.ValuetieredDate, cte2.ValuetieredDate) >= 90