我在 Oracle 中有一張表
| shift_id | 時間戳_(甲骨文) | 型別_ |
|---|---|---|
| 00000001 | 17/05/2022 08:00 | 0001 |
| 00000001 | 17/05/2022 09:00 | 0002 |
| 00000001 | 17/05/2022 09:15 | 0003 |
| 00000001 | 17/05/2022 12:00 | 0002 |
| 00000001 | 17/05/2022 13:00 | 0003 |
| 00000001 | 17/05/2022 15:00 | 0004 |
型別 1 是開始時間,型別 2 是暫停,型別 3 是暫停后繼續,型別 4 是結束時間
我想計算有效班次時間,我認為這樣做的一種方法是計算所有開始時間和結束時間的總和并減去它們,例如:
(sum(type 0002) sum(type 0004)) - (sum(type 0001) sum(type 0003))
但是如何在 oracle sql 中做到這一點?
我試過: select shift_id, sum(to_number_to_char(timestamp_,'sssss') where (type_ = 0002 or type is 0004) group by shift_id
然后我得到一個結果,如 00000001, 82442 但總和不是正確的總和,它只計算午夜后的秒數。
問題:如何得到如下結果:00000001, 05:45
uj5u.com熱心網友回復:
您可以使用 LAG 視窗函式計算時間差 a 并對其求和以獲得總量 -
CALC AS (SELECT d.*,
EXTRACT(DAY FROM timestamp_oracle - LAG(timestamp_oracle) OVER(PARTITION BY shift_id ORDER BY timestamp_oracle)) * 24 * 60
EXTRACT(HOUR FROM timestamp_oracle - LAG(timestamp_oracle) OVER(PARTITION BY shift_id ORDER BY timestamp_oracle)) * 60
EXTRACT(MINUTE FROM timestamp_oracle - LAG(timestamp_oracle) OVER(PARTITION BY shift_id ORDER BY timestamp_oracle)) tm
FROM data d)
SELECT shift_id,
TRUNC(ROUND(SUM(CASE WHEN type_ <> '0003' then tm else null end))/ 60) || ':' ||
MOD(ROUND(SUM(CASE WHEN type_ <> '0003' then tm else null end)), 60) tot_tm
from calc
GROUP BY shift_id;
演示。
uj5u.com熱心網友回復:
執行 LAG 可讓您訪問當前和以前的值
select
shift_id,
typ,
tstamp,
lag(typ) over ( order by tstamp ) prev_typ,
lag(tstamp) over ( order by tstamp ) prev_tstamp
from ...
一旦你有了它,你就可以根據需要制定間隔,例如
select
shift_id,
min(case when typ = 1 then tstamp end ) start_time
max(case when typ = 4 then tstamp end ) end_time
sum(case when typ in (2,4) then tstamp - prev_tstamp end )
from
( < above >
group by shift_id
或類似的,取決于你想如何切片和切塊
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/476575.html
