Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

I have column x in hh:mm format of datatype varchar in SQL Server and I want to perform sum on that 'x' column

I have column x in hh:mm format of datatype varchar in SQL Server and I want to perform sum on that x column.

I created a user-defined function to convert total min into hh:mm format.

Then I tried to perform sum to calculate total duration:

sum(cast(new_totalmin AS Int)) 
  1. also i want total of HH:mm exactly as example 4:20 +1:10

5:30 5 hour: 30 minute

  1. or i can do one thing here insted hh:mm i keep column as it is which is totalmin as int once sum cal insted of hh:mm (hh.mm which is in decimal also ok for me PSB it will be ok for me ':' or '.' format ) (60 min --> 1:00 --> 1.00

          90 min -->  1:30   -->1.30
         ---------------------------------
    

    sum --> 150 min -->2:30 --> 2.30)

but it did not work.

I got an error like

Conversion failed when converting the varchar value '01:00' to data type int

question from:https://stackoverflow.com/questions/65857237/i-have-column-x-in-hhmm-format-of-datatype-varchar-in-sql-server-and-i-want-to

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
DECLARE @SampleData AS TABLE (HourMinutes VARCHAR(10));

INSERT INTO @SampleData VALUES ('4:32');
INSERT INTO @SampleData VALUES ('5:28');
INSERT INTO @SampleData VALUES ('6:00');
INSERT INTO @SampleData VALUES ('7:10');

SELECT * FROM @SampleData

SELECT SUM(datediff(minute, 0, HourMinutes)) TotalMinute 
FROM @SampleData

You will get following output

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...