将 2 行合并为 1 行(开始时间和结束时间)
Combine 2 rows into 1 row (Start and End times)
我不知道该如何表达,但我在不同的行中有 Start
和 End
次,我想将它们合并成一行。在这个示例数据中,它基本上是 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个部分是:
- 对于同一个项目,我可能有多个 start/end 时间对(例如
如上面的项目 B), 可能在同一天背靠背或分开
- 我可能缺少开头或结尾
次。
谁能指出我正确的方向?我在 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;
这是某种间隙和孤岛问题。
我会用 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
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
我不知道该如何表达,但我在不同的行中有 Start
和 End
次,我想将它们合并成一行。在这个示例数据中,它基本上是 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个部分是:
- 对于同一个项目,我可能有多个 start/end 时间对(例如 如上面的项目 B), 可能在同一天背靠背或分开
- 我可能缺少开头或结尾 次。
谁能指出我正确的方向?我在 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;
这是某种间隙和孤岛问题。
我会用 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
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