2011-04-23 75 views
0

我有一個帶有TIME列的數據庫,並且想要將該時間的舍入版本與另一個時間列表。我如何將MySQL TIME四捨五入到最近的小時(不是日期時間/時間戳)

Example: 

[email protected] (mytest) desc ss; 
+-------+------+------+-----+---------+-------+ 
| Field | Type | Null | Key | Default | Extra | 
+-------+------+------+-----+---------+-------+ 
| t  | time | YES |  | NULL |  | 
+-------+------+------+-----+---------+-------+ 
1 row in set (0.01 sec) 

[email protected] (mytest) desc tt; 
+-------+------+------+-----+---------+-------+ 
| Field | Type | Null | Key | Default | Extra | 
+-------+------+------+-----+---------+-------+ 
| s  | time | YES |  | NULL |  | 
+-------+------+------+-----+---------+-------+ 
1 row in set (0.00 sec) 

[email protected] (mytest) select * from ss; 
+----------+ 
| t  | 
+----------+ 
| 16:00:00 | 
+----------+ 
1 row in set (0.00 sec) 

[email protected] (mytest) select * from tt; 
+----------+ 
| s  | 
+----------+ 
| 15:45:00 | 
| 16:00:00 | 
| 19:30:00 | 
| 17:45:00 | 
| 18:00:00 | 
| 19:30:00 | 
+----------+ 

需要一個查詢加盟SS和TT圓潤的地方= tt.s ss.t

回答

0

假設ss.t已經四捨五入:

SELECT * 
FROM tt 
    JOIN ss 
    ON (SUBTIME(ss.t, '00:30:00.0') <= tt.s) 
    AND (tt.s < ADDTIME(ss.t, '00:30:00.0') ) 
1

我的解決方案是轉換爲秒,做我的數學,然後轉換回時間。

select s,hour(s)*3600+minute(s)*60+second(s) time_as_seconds from tt; 
+----------+-----------------+ 
| s  | time_as_seconds | 
+----------+-----------------+ 
| 15:45:00 |   56700 | 
| 16:00:00 |   57600 | 
| 19:30:00 |   70200 | 
| 17:45:00 |   63900 | 
| 18:00:00 |   64800 | 
| 19:30:00 |   70200 | 
+----------+-----------------+ 
6 rows in set (0.00 sec) 

對於一個小的數據集,我只是計算每個表的「秒」值並進行比較。所以,我最終會加盟:

1800 * round((hour(tt.s)*3600+minute(tt.s)*60+second(tt.s))/1800) 

hour(ss.t)*3600+minute(ss.t)*60+second(ss.t) 

但如果有很多行的基準表(T)或有上t.ss指數可能加速在查詢之後,我們必須返回時間值。 SEC_TO_TIME解決了這個問題。

所以,這裏是一個例子四捨五入到最接近的半小時(因此1800)

select 
s, 
hour(s)*3600+minute(s)*60+second(s) time_as_seconds, 
1800 * round((hour(s)*3600+minute(s)*60+second(s))/1800) rounded_to_half_hour, 
sec_to_time(1800 * round((hour(s)*3600+minute(s)*60+second(s))/1800)) rounded_time 
from tt; 

+----------+-----------------+----------------------+--------------+ 
| s  | time_as_seconds | rounded_to_half_hour | rounded_time | 
+----------+-----------------+----------------------+--------------+ 
| 15:45:00 |   56700 |    57600 | 16:00:00  | 
| 16:00:00 |   57600 |    57600 | 16:00:00  | 
| 19:30:00 |   70200 |    70200 | 19:30:00  | 
| 17:45:00 |   63900 |    64800 | 18:00:00  | 
| 18:00:00 |   64800 |    64800 | 18:00:00  | 
| 19:30:00 |   70200 |    70200 | 19:30:00  | 
+----------+-----------------+----------------------+--------------+ 
6 rows in set (0.00 sec) 
+0

您沒有使用UNIT_TIMESTAMP功能的原因是什麼? – Selah 2015-04-28 15:37:18

相關問題