我們在開發過程中總會遇到這樣的情況,一行資料中,有id、組、開始時間、結束時間。但是開始時間和結束時間肯定會出現時間重疊問題,比如說下面這種情況。
我們先找出時間重疊的公式:
可以發現:
公式如下:
a.alarm_type_id = b.alarm_type_id and
a.start_time <= b.stop_time and
a.stop_time >= b.start_time and
a.id <> b.id
詳細的sql語句:
select
distinct b.
*from
`time_table` a,
`time_table` b
where
a.id <> b.id and
a.alarm_type_id = b.alarm_type_id and
a.start_time <= b.stop_time and
a.stop_time >= b.start_time
查詢出時間不重疊的資料:
select
*from
time_table a
where a.id notin(
select
distinct b.id
from
`time_table` a,
`time_table` b
where
a.id <> b.id and
a.alarm_type_id = b.alarm_type_id and
a.start_time <= b.stop_time and
a.stop_time >= b.start_time );
統計重疊時間的方法,我們可以先分組,然後獲取分組後的資料的最小時間和最大時間,之後做差就能求出時間和。
select
alarm_type_id,
unix_timestamp(
max(k1.stop_time)
)-unix_timestamp(
min(k1.start_time)
)from
(select
distinct b.
*from
`time_table` a,
`time_table` b
where
a.id <> b.id and
a.alarm_type_id = b.alarm_type_id and
a.start_time <= b.stop_time and
a.stop_time >= b.start_time
) k1 group
by k1.alarm_type_id;
統計不重疊時間的方法。
select
alarm_type_id,
sum(unix_timestamp(stop_time)
- unix_timestamp(start_time)
) time_sum
from
(select
*from
time_table a
where a.id notin(
select
distinct b.id
from
`time_table` a,
`time_table` b
where
a.id <> b.id and
a.alarm_type_id = b.alarm_type_id and
a.start_time <= b.stop_time and
a.stop_time >= b.start_time
)) k2 group
by alarm_type_id;
接下來可以直接整合統計,沒什麼難度,直接兩條語句連起來。然後分組查詢,進行sum。
問題:會出現存在本週第一天和上週最後一天存在跨天的情況,可以直接擷取進行統計。
sql語句中的時間處理
我們在用sql語句處理資料庫資料時難免會遇到insert或者update一條資料,資料中的某個欄位是時間格式,那我們怎麼把引數的形式在sql語句中設定成時間格式呢,這裡記錄一下。update t bill contract bill set property fee 480.0,rent fee 6...
在同乙個sql語句中,統計不同條件的Count數量
前幾天幫同事優化了個sql,原寫法使用多個子查詢這裡不再重現了,大家都遇到過這樣一種情況,在專案後期的維護中,修改別人的sql 超過30行的語句,多層子查詢,讀起來很坑,時間久的專案伴隨著人員的流通,你可能就不知道原作者寫這一堆的sql是幹什麼用的,當然碰到部分有注釋習慣的朋友還是好點的,過長的sq...
SQL語句中時間格式的轉換
sql server中文版的預設的日期欄位datetime格式是yyyy mm dd thh mm ss.mmm 例如 select getdate 2004 09 12 11 06 08.177 這對於在要不同資料庫間轉移資料或者習慣oracle日期格式yyyy mm dd hh24 mi ss的...