我試圖從另一個日期中減去一個日期但有問題:
SELECT MIN(date) AS first_day,
MAX(date) AS last_date,
((MAX(date)) - (MIN(date))) AS totaL_days
FROM dates;
有人可以澄清下面回傳的數字的數字格式嗎?
------------
| total_days |
------------
| 29001900 |
我曾嘗試使用 DATEDIFF,但這會將天數四舍五入到最接近的整數,我需要對資料進行進一步計算。四舍五入意味著我的解決方案有點偏離。在 DB 版本中,我使用 DATEDIFF() 只需要兩個引數,所以就我所知,它總是需要幾天,如果我嘗試使用小時,我會收到錯誤訊息。
uj5u.com熱心網友回復:
SELECT DATEDIFF
(
SELECT MAX(date) FROM dates,
SELECT MIN(date) FROM dates
)
AS totaL_days;
應該做的伎倆。
uj5u.com熱心網友回復:
我假設你的 RDBMS 是一個 MySql。
那么你得到的數字就是這兩個日期時間之間的秒數。
因為如果你減去 2 個 DATE 型別,你會得到它們之間的天數。
有超過DATEDIFF與作業。
測驗資料
create table mytest ( id int auto_increment primary key, date_col date not null, datetime_col datetime not null ); insert into mytest(date_col, datetime_col) values ('2021-06-16', '2021-06-16 14:15:30') ,('2021-07-16', '2021-07-16 19:06:15')
使用日期進行測驗
select min(date_col) as min_date , max(date_col) as max_date , max(date_col) - min(date_col) as subtracted , datediff(max(date_col), min(date_col)) as days from mytestmin_date | 最大日期 | 減去 | 天 :--------- | :--------- | ---------: | ---: 2021-06-16 | 2021-07-16 | 100 | 30
使用日期時間進行測驗
select min(datetime_col) as min_date , max(datetime_col) as max_date , max(datetime_col) - min(datetime_col) as seconds , datediff(max(datetime_col), min(datetime_col)) as days from mytestmin_date | 最大日期 | 秒 | 天 :------------------- | :------------------- | --------: | ---: 2021-06-16 14:15:30 | 2021-07-16 19:06:15 | 100049085 | 30
使用 sec_to_time 并提取
select seconds , sec_to_time(seconds) as tm , extract(day from sec_to_time(seconds)) as days from ( select max(datetime_col) - min(datetime_col) as seconds from mytest ) q秒 | tm | 天 --------: | :-------- | ---: 100049085 | 838:59:59 | 30
db<>在這里擺弄
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/366515.html
標籤:sql
上一篇:僅使用SQL輸出特定值
