我有以下查询。
select cast(dateadd(minute, datediff(minute, TimeIn, TimeOut), 0) as time(0) )
我从 hrs-min-seconds 格式的两列中得到结果。我只想要 min 的格式。所以02:47:00
会读167
。
我有以下查询。
select cast(dateadd(minute, datediff(minute, TimeIn, TimeOut), 0) as time(0) )
我从 hrs-min-seconds 格式的两列中得到结果。我只想要 min 的格式。所以02:47:00
会读167
。
SQL 服务器查询:
SELECT cast(substring('02:47:00',1,2) AS int)*60+
cast(substring('02:47:00',4,2) AS int)+
cast(substring('02:47:00',7,2) AS int)/60.0 AS minutes
MYSQL 查询:
SELECT TIME_TO_SEC('02:47:00') / 60
结果:
| MINUTES |
-----------
| 167 |
declare @Time DATETIME = '01:05:00'
select ((DATEPART(HOUR, @Time)*60) + (DATEPART(MINUTE, @Time)))
试试这个:
datediff(minute, 0, '02:47')
对于 SQL Server(也适用于 2005):
select Datediff(mi,convert(datetime,'00:00:00',108), convert(datetime,'02:47:00',108))
扩展贾斯汀的答案。这允许小时数大于 2 位的情况。
declare @time varchar(50) = '102:47:05'
SELECT cast(right(@time,2) AS int)+
cast(left(right(@time,5),2) AS int)*60+
cast(left(@time,len(@time)-6) AS int)*3600 AS seconds,
(cast(right(@time,2) AS int)+
cast(left(right(@time,5),2) AS int)*60+
cast(left(@time,len(@time)-6) AS int)*3600)/60.0 AS minutes
结果:
seconds minutes
----------- ---------------------------------------
370025 6167.083333
SELECT DATEDIFF(minute,CAST('00:00' AS TIME), CAST('02:47' AS TIME)) AS difference
给你:
| DIFFERENCE |
--------------
| 167 |
不幸的是,如果您想对超过 24 小时的值使用 DATEPART 函数,您将收到错误消息:
从字符串转换日期和/或时间时转换失败。"
您可以使用以下代码对其进行测试:
declare @Time DATETIME = '32:00:00'
select ((DATEPART(HOUR, @Time)*60) + (DATEPART(MINUTE, @Time)))
为了解决这个问题,我使用了另一种方法:
declare @tbl table(WorkHrs VARCHAR(8))
insert into @tbl(WorkHrs) values ('02:47:00')
insert into @tbl(WorkHrs) values ('32:00:00')
-- Sum in minutes
SELECT TRY_CAST(([HOURS] * 60) + [MINUTES] + ([SECOND] / 60) AS INT) as TotalInMinutes
FROM (
SELECT
-- Use this aproach to get separated values
SUBSTRING(WorkHrs,1,CHARINDEX(':',WorkHrs)-1) AS [HOURS],
SUBSTRING(WorkHrs,4,CHARINDEX(':',WorkHrs)-1) AS [MINUTES],
SUBSTRING(WorkHrs,7,CHARINDEX(':',WorkHrs)-1) AS [SECOND] -- probably you can ignore this one
FROM @tbl
)
tbl
-- Sum in seconds
SELECT TRY_CAST(([HOURS] * 3600) + ([MINUTES] * 60) + [SECOND] AS INT) as TotalInSeconds
FROM (
SELECT
-- Use this aproach to get separated values
SUBSTRING(WorkHrs,1,CHARINDEX(':',WorkHrs)-1) AS [HOURS],
SUBSTRING(WorkHrs,4,CHARINDEX(':',WorkHrs)-1) AS [MINUTES],
SUBSTRING(WorkHrs,7,CHARINDEX(':',WorkHrs)-1) AS [SECOND]
FROM @tbl
)
tbl
此代码将返回如下:
$time = '02:47:00';
$time = explode(":",$time);
$total = ($a[0]*60)+$a[1];
echo 'Minutes : '.$total;<br>
echo 'Seconds : '.$a[2];