我的问题非常类似于这个问题:Find start and end dates when one field changes
但是,我无法根据我的情况调整代码。任何帮助将不胜感激。
我的数据包含ID,名为Type的变量和两个日期时间字段(一个名为Start,另一个名为Stop)。这可以在这里找到:http://sqlfiddle.com/#!6/35f43
列Start和Stop的值可以连续运行,我想要按ID和Type组合这些记录。我目前遇到的问题是,如果“开始”和“停止”日期时间不连续,我需要将ID和类型分开。
例如,在SQLFiddle链接的数据中,ID' 3'目前有五个类型为A的记录,其间有一个类型为B的记录。
ID Start Stop Type 3 2010-03-12 05:10:02.0000000 2010-03-20 12:00:00.0000000 A 3 2010-03-20 12:00:00.0000000 2010-04-07 09:46:30.0000000 A 3 2010-04-07 09:46:30.0000000 2010-05-01 08:13:42.0000000 B 3 2010-05-01 08:13:42.0000000 2010-07-04 09:30:32.0000000 A 3 2010-07-04 09:30:32.0000000 2010-07-06 11:41:38.0000000 A 3 2010-07-06 11:41:38.0000000 2010-07-09 12:51:30.0000000 A
我需要将其显示为:
ID Start Stop Type 3 2010-03-12 05:10:02.0000000 2010-04-07 09:46:30.0000000 A 3 2010-04-07 09:46:30.0000000 2010-05-01 08:13:42.0000000 B 3 2010-05-01 08:13:42.0000000 2010-07-09 12:51:30.0000000 A
有什么想法吗?
答案 0 :(得分:0)
这样做:
@CucumberOptions( features = "src/test/resources/features",
glue="com.bnymellon.sse.ui.step_definitions", tags = {"@demo"},
monochrome = true, plugin = {"html:output/HTML_Reports/"} )
答案 1 :(得分:0)
;WITH CTE_T AS (
select *,ROW_NUMBER() OVER(ORDER BY Start) r
from T A
where not exists(
select * from T B
WHERE B.ID = A.ID AND B.Start = A.Stop AND B.Type = A.Type
)
UNION ALL
SELECT B.*,A.R fROM CTE_T A
JOIN T B ON A.Start = B.Stop
AND B.ID = A.ID AND B.Type = A.Type
)
SELECT ID,MIN(Start) [Start],MAX(Stop) [Stop],Type FROM CTE_T
GROUP BY ID,TYPE,R