将 2 行合并为 1 行(开始时间和结束时间)

Combine 2 rows into 1 row (Start and End times)

我不知道该如何表达,但我在不同的行中有 StartEnd 次,我想将它们合并成一行。在这个示例数据中,它基本上是 tracking/logging 个项目时间:

Project  Type    Time
A        Start   1:00
A        End     1:10
B        Start   2:00
B        End     2:10
B        Start   2:30
B        End     2:45
C        End     3:00
D        Start   3:10
D        End     3:20

我要找的是这样的:

Project  Start    End
A        1:00     1:10
B        2:00     2:10
B        2:30     2:45
C        NULL     1:10
D        3:10     3:20

奇数的2个部分是:

谁能指出我正确的方向?我在 Whosebug 上找不到任何具有这些相同要求的内容。

我们可以在ROW_NUMBER:

的帮助下在这里尝试使用旋转逻辑
WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Project, Type ORDER BY Time) rn
    FROM yourTable
)

SELECT
    Project,
    MAX(CASE WHEN Type = 'Start' THEN Time END) AS Start,
    MAX(CASE WHEN Type = 'End'   THEN Time END) AS [End]
FROM cte
GROUP BY
    Project,
    rn
ORDER BY
    Project,
    rn;

Demo

这是某种间隙和孤岛问题。

我会用 lag() 和 window sum() 来解决这个问题。每当连续的记录类型不是 'Start' 后跟 'End'.

时,一个新组就会开始
select 
    project, 
    min(case when type = 'Start' then time end) Start,
    max(case when type = 'End' then time end) [End]
from (
    select
        t.*,
        sum(case when type = 'End' and lag_type = 'Start' then 0 else 1 end) 
            over(partition by project order by time) grp
    from (
        select
            t.*,
            lag(type) over(partition by project order by time) lag_type
        from mytable t
    ) t
) t
group by project, grp
order by project, grp

Demo on DB Fiddle:

Project | Start | End 
:------ | :---- | :---
A       | 1:00  | 1:10
B       | 2:00  | 2:10
B       | 2:30  | 2:45
C       | null  | 3:00
D       | 3:10  | 3:20