views:

689

answers:

4

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?

A: 

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.

Cyril Gupta
A: 

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.

Jonathan Leffler
A: 

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;
Seiti
A: 
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);
does not work server-side
usr