如何添加在 SQL 服务器中存储为十进制的两个时间值
How to add two time values stored as decimal in SQL Server
我需要添加两列,将时间值存储为小数
例子:
1.) 8.30+0.32 = 9.02(输出应该是 9.03 而不是 8.62)
上面提到的例子工作正常,是下面 SQL.
的实际输出
我写了下面的 SQL 主要工作正常,但我发现很少有添加不正确的情况
例子:3.57+5.25=18.44
SELECT
case when B.Column_B is null then A.Column_A
when B.Column_B is not null then
replace(CONVERT(varchar(5),
DATEADD(ss,(SUM((DATEPART(hh, replace(isnull(a.Column_A,0.00),'.',':'))*3600) + (DATEPART(mi,replace(isnull(a.Column_A,0.00),'.',':'))*60)) +
SUM((DATEPART(hh, replace(isnull(b.Column_B,0.00),'.',':'))*3600) + (DATEPART(mi,replace(isnull(b.Column_B,0.00),'.',':'))*60))),0),108) ,':','.')
End as "Total_Hours"
在上述案例中,我找不到问题出在哪里。这里有什么问题或者有更好的方法来处理这个添加
试试这个:
DECLARE @Value01 DECIMAL(9,2) = 8.30
,@value02 DECIMAL(9,2) = 0.32;
SELECT CONCAT
(
(DATEDIFF(MINUTE, '0:00:00', CAST(REPLACE(@Value01, '.', ':') AS TIME)) + DATEDIFF(MINUTE, '0:00:00', CAST(REPLACE(@value02, '.', ':') AS TIME))) / 60
,'.'
,RIGHT((DATEDIFF(MINUTE, '0:00:00', CAST(REPLACE(@Value01, '.', ':') AS TIME)) + DATEDIFF(MINUTE, '0:00:00', CAST(REPLACE(@value02, '.', ':') AS TIME))) % 60 + 100, 2)
);
首先,转换为TIME
并得到总分钟数。然后,将分钟格式化为 Time
但使用 .
代替 :
.
代码
declare @v1 DECIMAL(9,3) = 4.369, -- 9 characters with 3 decimal places.
@v2 DECIMAL(9,3) = 3.368 -- 9 characters with 3 decimal places.
print @v1 + @v2
输出
7.737
我需要添加两列,将时间值存储为小数 例子: 1.) 8.30+0.32 = 9.02(输出应该是 9.03 而不是 8.62)
上面提到的例子工作正常,是下面 SQL.
的实际输出我写了下面的 SQL 主要工作正常,但我发现很少有添加不正确的情况
例子:3.57+5.25=18.44
SELECT
case when B.Column_B is null then A.Column_A
when B.Column_B is not null then
replace(CONVERT(varchar(5),
DATEADD(ss,(SUM((DATEPART(hh, replace(isnull(a.Column_A,0.00),'.',':'))*3600) + (DATEPART(mi,replace(isnull(a.Column_A,0.00),'.',':'))*60)) +
SUM((DATEPART(hh, replace(isnull(b.Column_B,0.00),'.',':'))*3600) + (DATEPART(mi,replace(isnull(b.Column_B,0.00),'.',':'))*60))),0),108) ,':','.')
End as "Total_Hours"
在上述案例中,我找不到问题出在哪里。这里有什么问题或者有更好的方法来处理这个添加
试试这个:
DECLARE @Value01 DECIMAL(9,2) = 8.30
,@value02 DECIMAL(9,2) = 0.32;
SELECT CONCAT
(
(DATEDIFF(MINUTE, '0:00:00', CAST(REPLACE(@Value01, '.', ':') AS TIME)) + DATEDIFF(MINUTE, '0:00:00', CAST(REPLACE(@value02, '.', ':') AS TIME))) / 60
,'.'
,RIGHT((DATEDIFF(MINUTE, '0:00:00', CAST(REPLACE(@Value01, '.', ':') AS TIME)) + DATEDIFF(MINUTE, '0:00:00', CAST(REPLACE(@value02, '.', ':') AS TIME))) % 60 + 100, 2)
);
首先,转换为TIME
并得到总分钟数。然后,将分钟格式化为 Time
但使用 .
代替 :
.
代码
declare @v1 DECIMAL(9,3) = 4.369, -- 9 characters with 3 decimal places.
@v2 DECIMAL(9,3) = 3.368 -- 9 characters with 3 decimal places.
print @v1 + @v2
输出
7.737