Question

I have a time field in a mssql 2008 database that I want to do something to the effect of:

Timespent = x.sum(x => x.AmountOfTime);

Where AmountOfTime is a time MSSQL field. Sum seems to only work on decimals, how can I add these columns?

Was it helpful?

Solution

You probably want to convert the periods to intervals - if necessary, by subtracting the start time from the end time. Note that the TIME type represents an instant, not a duration. In standard SQL, you want INTERVAL HOUR TO SECOND. I'm not sure whether Microsoft supports that - there are other major DBMS that do not. If you are stuck with TIME, you should be able to subtract TIME '00:00:00' from the values and get something workable (that would be an INTERVAL).

One particular advantage of intervals is that you can indeed add them up via SUM.

For the details, you can manual bash at MSDN (or via Google) as well as I can.

OTHER TIPS

If SQL construct doesn't support this, you can't... Why don't you make a special field which has a numeric representation of the time, and then you can add it together using SQL.

public static class Extentions
{
    public static TimeSpan Sum<T>(this IEnumerable<T> items, Func<T, TimeSpan> selector)
    {
        var summ = TimeSpan.Zero;
        foreach(T item in items)
        {
            summ += selector(item);
        }
        return summ;
    }
}

var timespent = foo.Sum(f => f.finishdatetime - f.startdatetime);

I solved this using the following method, given that you have a start and finish datetime on your table:

public TimeSpan AmountOfTime(IQueryable<Something> iq)
{
    TimeSpan ts = TimeSpan.Zero;
    foreach (Something a in iq.ToList())
        ts += (a.finishdatetime - a.startdatetime);
    return ts
}

Then you can use it to get the total number of hours:

double foo = AmountOfTime(datacontext.Where(conditions)).TotalHours;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top