我有一个这样的桌子制作。
id [PK integer] order_id [integer] start [timestamp] end [timestamp] count [integer]
1 1 10:00 11:00 15
2 1 11:00 12:00 1
3 2 12:00 13:00 2
4 3 13:00 14:00 10
5 1 14:00 15:00 4
6 1 15:00 16:00 7
7 1 16:00 17:00 3
8 3 17:00 18:00 21
9 1 18:00 19:00 5
我喜欢得到的结果:
order_id start end count
1 10:00 12:00 16
2 12:00 13:00 2
3 13:00 14:00 10
1 14:00 17:00 14
3 17:00 18:00 21
1 18:00 19:00 5
我尝试的最后一件事:
WITH lp AS (
SELECT *,LEAD(order_id) OVER(ORDER BY start) AS next_id
FROM production
)
SELECT order_id,
MIN(start) AS start,
MAX(end) AS end,
SUM(count) AS count
FROM lp
WHERE order_id = next_id
GROUP BY order_id
ORDER BY MIN(start);
我知道查询不正确。如何包含表格的第一行 有什么想法如何修复吗? 非常感谢您的帮助。
ordered_data
CTE 的一部分。grp
CTE中获得唯一的
grouped_data
WITH ordered_data AS (
SELECT
id,
order_id,
start,
end1,
count,
LAG(order_id) OVER (ORDER BY start) AS prev_order_id
FROM test
),
grouped_data AS (
SELECT
id,
order_id,
start,
end1,
count,
SUM(CASE WHEN order_id = prev_order_id THEN 0 ELSE 1 END) OVER (ORDER BY start) AS grp
FROM ordered_data
)
SELECT
order_id,
MIN(start) AS start,
MAX(end1) AS end1,
SUM(count) AS count
FROM grouped_data
GROUP BY order_id, grp
ORDER BY MIN(start);
订单_id | 开始 | 结束1 | 数 |
---|---|---|---|
1 | 2023-12-19 10:00:00 | 2023-12-19 12:00:00 | 16 |
2 | 2023-12-19 12:00:00 | 2023-12-19 13:00:00 | 2 |
3 | 2023-12-19 13:00:00 | 2023-12-19 14:00:00 | 10 |
1 | 2023-12-19 14:00:00 | 2023-12-19 17:00:00 | 14 |
3 | 2023-12-19 17:00:00 | 2023-12-19 18:00:00 | 21 |
1 | 2023-12-19 18:00:00 | 2023-12-19 19:00:00 | 5 |