0

I use the following sql to calculate the duration in the first query.

CDate(TimeSerial(Val([EndTime])\100,Val([EndTime]) Mod 100,0)-TimeSerial(Val([StartTime])\100,Val([StartTime]) Mod 100,0))) AS Duration

And get the following which is good enter image description here

And now, I would like to further calculate the total time of different lessons within a week in another query. Something like sum(iif(lesson="math",duration,0))

But since it's time data type sql server doesn't let me use the sum function.

I tried the following sql.

sum(hour(duration) + minute(duration)) AS Total_time

But it isn't what I expect because I would like to keep the original format with some criteria.

Is there a neat way to do so? Thank you.

4
  • What's in your time fields? You pretty much never want to Val a date or time field Commented Aug 5, 2020 at 13:42
  • string, like 1330 to 1530 Commented Aug 5, 2020 at 13:51
  • It sounds like this question actually boils down to: How do I format a date with more than 24 hours as Hours:Days. Is that correct? Commented Aug 5, 2020 at 14:04
  • not really. The problem is that is there an easy way to sum over the duration in the format of hh:mm:ss Commented Aug 6, 2020 at 1:36

2 Answers 2

1

First, just get the numeric duration:

TimeSerial(Val([EndTime])\100,Val([EndTime]) Mod 100,0)-TimeSerial(Val([StartTime])\100,Val([StartTime]) Mod 100,0) AS Duration

This you can sum and convert to DateTime:

CDate(Sum([duration])) AS Total_time

Example:

Data:

Data

Queries:

SELECT 
    StartTime, 
    EndTime, 
    TimeSerial(Val([EndTime])\100,Val([EndTime]) Mod 100,0)-TimeSerial(Val([StartTime])\100,Val([StartTime]) Mod 100,0) AS Duration
FROM 
    tTest;
SELECT 
    Count(*) AS Slots, 
    CDate(Sum([Duration])) AS TotalHours
FROM 
    qTest;

Result:

Result

Sign up to request clarification or add additional context in comments.

1 Comment

It certainly does. See extended answer, please.
1

I would recommend just accepting the total time in seconds or decimal hours:

select datediff("s", starttime, endtime) as diff_seconds,
       datediff("s", starttime, endtime) / (60 * 60.0) as diff_hours
   

3 Comments

starttime and endtime are string
@user13851309 . . . Convert them to date/times then for the datediff().
I change the question a bit which was confusing. I wanna calculate the total time in another query based on the duration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.