如何计算具有时间跨度类型的列的总和 [英] how to calculatet sum of a column with timespan type

查看:89
本文介绍了如何计算具有时间跨度类型的列的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在sp中我需要总结一列timepan格式的valus,保存为Varchar数据类型。

(由于某些原因)

我怎么能将每个值转换为时间跨度,然后将其与其他值相加

表结构

==================== =========

Field ------------数据类型

========== ===================

名称------------ varchar(255)

A栏------ varchar(50)







列A的值(小时:分钟)

=============================

30:23

140:12

15:56



解决方案

您将需要解析字符串,分割小时和分钟,然后添加小时并添加分钟,并将分钟数除以60以查看是否需要添加任何小时,并保持余数为分钟。

   -    CAST (PARSENAME(REPLACE(ColumnA,:,。),1)as INT)为您提供分钟 
- < span class =code-comment> CAST(PARSENAME(REPLACE(ColumnA,:,。),2)as INT)为您提供小时

- @ totalhours = @sumhours + @summinutes / 60
- @ totalminutes = @summinutes%60

- 因此查询变为:
SELECT
SUM(CAST( PARSENAME (REPLACE(ColumnA, ), 2 )< span class =code-keyword> as INT ))+(SUM(CAST( PARSENAME (REPLACE(ColumnA, ), 1 as INT ))/ 60 as totalhours,
SUM(CAST( PARSENAME (REPLACE(ColumnA, ), 1 as INT ))% 60 remainingminutes
FROM
tablename


Hi, In a sp I need to sum valus of a column of timespan format which saved as Varchar datatype.
(because of some reasons)
How can I convert each value to timespan and then sum that with other values
Table structure
=============================
Field ------------ Data Type
=============================
Name ------------ varchar(255)
Column A ------ varchar(50)



values of column A(hour:minute)
=============================
30:23
140:12
15:56
.
.

解决方案

You will need to parse the string, splitting hours and minutes, then add the hours and add the minutes, and divide minutes by 60 to see if you need to add any hours, and keep the remainder as minutes.

-- CAST(PARSENAME(REPLACE(ColumnA, ":", "."),1) as INT) gives you the minutes
-- CAST(PARSENAME(REPLACE(ColumnA, ":", "."),2) as INT) gives you the hours

--@totalhours = @sumhours + @summinutes / 60
--@totalminutes = @summinutes % 60

--So the query becomes:
SELECT 
  SUM(CAST(PARSENAME(REPLACE(ColumnA, ":", "."),2) as INT)) + (SUM(CAST(PARSENAME(REPLACE(ColumnA, ":", "."),1) as INT)) / 60) as totalhours,
  SUM(CAST(PARSENAME(REPLACE(ColumnA, ":", "."),1) as INT)) % 60 as remainingminutes
FROM 
  tablename


这篇关于如何计算具有时间跨度类型的列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆