Sum a DATETIME field

Just noticed it isn't straight forward to SUM a DATETIME fields.
I’ve used the following code to get the time, how do I convert the output back to a DATETIME field?
declare @T table
total_hours_worked datetime
insert into @T values ('01:00:00')
insert into @T values ('01:30:00')
insert into @T values ('03:35:00')
select *
from @T
select SUM((DATEPART(hh,total_hours_worked)*60)+DATEPART(mi,total_hours_worked)+(DATEPART(ss,total_hours_worked)/(60.0)))/60.0 as TotalHours from @T
Thanks,

I should have added the disclaimer that my solution would require total_hours_worked to be stored as either a float or a varchar to be used with the function I described above.   The completed functions would be similar to 
CREATE FUNCTION dbo.TimeSpan_CreateFromString
@pFormattedTimeSpan varchar(128) = null
RETURNS float(53)
with returns null on null input AS
BEGIN
declare @DayPortion int
,@HourPortion int
,@MinutePortion int
,@SecondPortion decimal(6,4)
declare @l int
declare @s2 varchar(128)
DECLARE @Result float(53)
select @s2=LTRIM(rtrim(@pFormattedTimeSpan))
set @l = LEN(@s2)
declare @i int
if CHARINDEX('.',@s2,1) < CHARINDEX(':',@s2,1)
begin
set @i = CHARINDEX('.',@s2,1)
select @DayPortion =
case CHARINDEX('.',@s2)
when 0 then 0
else
case ISNUMERIC(SUBSTRING(@s2,1,CHARINDEX('.',@s2)-1))
when 1 then CAST(SUBSTRING(@s2,1,CHARINDEX('.',@s2)-1) as int)
else 0
end
end;
set @s2=ltrim(rtrim(SUBSTRING(@s2,@i+1,@l-(@i))))
end
else
begin
set @DayPortion=0
end
-- ** debug: select @i, @l, @s2
--select CHARINDEX(':',@s2,1) [c1], CHARINDEX(':',@s2,CHARINDEX(':',@s2,1)+1) [c2], CHARINDEX(':',@s2,(CHARINDEX(':',@s2,CHARINDEX(':',@s2,1)+1))+1) [c3]
set @i = CHARINDEX(':',@s2,1)
select @HourPortion =
case CHARINDEX(':',@s2,1)
when 0 then 0
else
case ISNUMERIC(SUBSTRING(@s2,1,CHARINDEX(':',@s2,1)-1))
when 1 then CAST(SUBSTRING(@s2,1,CHARINDEX(':',@s2,1)-1) AS int)
else null
end
end
set @s2=ltrim(rtrim(SUBSTRING(@s2,@i+1,@l-(@i))))
-- ** debug: select @i, @l, @s2
set @i = CHARINDEX(':',@s2,1)
select @MinutePortion =
case CHARINDEX(':',@s2,1)
when 0 then 0
else
case ISNUMERIC(SUBSTRING(@s2,1,CHARINDEX(':',@s2,1)-1))
when 1 then CAST(SUBSTRING(@s2,1,CHARINDEX(':',@s2,1)-1) AS int)
else null
end
end
set @s2=ltrim(rtrim(SUBSTRING(@s2,@i+1,@l-(@i))))
-- ** debug: select @i, @l, @s2
set @i = CHARINDEX(':',@s2,1)
select @SecondPortion =
case ISNUMERIC(@s2)
when 0 then null
else CAST(@s2 as decimal(6,4))
end
SELECT @Result = dbo.TimeSpan_CreateFromParts(@DayPortion,@HourPortion,@MinutePortion,@SecondPortion);
RETURN @Result
END
GO
I changed the function names to make them more consistent.

Similar Messages

  • Sum of a field in ALV List

    Hello Guys,
    I'm using 'REUSE_ALV_GRID_DISPLAY' in my prog.
    There is a field in output table which is of type P(8) Decimals 3.
    When I'm trying to get the sum of this field in ALV Display it gives the message " Desired operation cannot be performed for column 'Converted Quantity' ".
    I have also tried do_sum = 'X'.
    But it is not working. Please help guys.
    Regards,
    Abhinav

    Thanks a lot guys for your inputs.
    The program is working now.
    Now I'm using :
      CLEAR wa_fieldcat.
      wa_fieldcat-fieldname = 'QUAN'.
    *  wa_fieldcat-ref_tabname = 'I_OUT2'.
    *  wa_fieldcat-tabname = 'I_OUT2'.
      wa_fieldcat-qfieldname = 'MEAS'.
      wa_fieldcat-qtabname = 'I_OUT2'.
      wa_fieldcat-outputlen = '15'.
      wa_fieldcat-seltext_l = text-052.
      APPEND wa_fieldcat TO i_fieldcat.
    The program is working fine now.
    I have commented tabname and -ref_tabname , and the program is working fine now.
    Thanks a lot.

  • Dump when summing up CURR field in ALV GRID display

    Hi All,
    I am getting dump when I try to sum the CURR field in my ALV Grid Display. The field is of CURR 23.  I am using classes and methods to display alv grid.
    I tried passing <fs_fieldcat>-do_sum = 'X'. When I did this, it is dumping without even displaying the alv grid.
    Here is the part it is throwing dump:
            ls_lvc_data-value = space.
            clear ls_lvc_data-style.
            loop at it_fcat_local assigning <ls_fcat>
                    where tech ne 'X' and no_out ne 'X'.
              if l_invisible eq 'X'.
                clear l_invisible.
                if <ls_fcat>-do_sum is initial.
                  continue.
                else.
                  clear ls_lvc_data-col_pos.
                endif.
              endif.
              add 1 to ls_lvc_data-col_pos.
              assign component <ls_fcat>-fieldname
                               of structure <ls_data> to <l_field_value>.
              _if sy-subrc ne 0.
                message x000(0k).
              endif._
    Regards,
    Guru

    Thomas,
    Here is the dump:
    Runtime Errors         MESSAGE_TYPE_X
    Date and Time          10/22/2010 23:30:53
    Short text
    The current application triggered a termination with a short dump.
    What happened?
    The current application program detected a situation which really
    should not occur. Therefore, a termination with a short dump was
    triggered on purpose by the key word MESSAGE (type X).
    Error analysis
    Short text of error message:
    Long text of error message:
    Technical information about the message:
    Message class....... "0K"
    Number.............. 000
    Variable 1.......... " "
    Variable 2.......... " "
    Variable 3.......... " "
    Variable 4.......... " "
    How to correct the error
    Probably the only way to eliminate the error is to correct the program.
    If the error occures in a non-modified SAP program, you may be able to
    find an interim solution in an SAP Note.
    If you have access to SAP Notes, carry out a search with the following
    keywords:
    "MESSAGE_TYPE_X" " "
    "SAPLSLVC" or "LSLVCF36"
    "FILL_DATA_TABLE"
    If you cannot solve the problem yourself and want to send an error
    notification to SAP, include the following information:
    1. The description of the current problem (short dump)
    To save the description, choose "System->List->Save->Local File
    (Unconverted)".
    2. Corresponding system log
    Display the system log by calling transaction SM21.
    Restrict the time interval to 10 minutes before and five minutes
    after the short dump. Then choose "System->List->Save->Local File
    (Unconverted)".
    3. If the problem occurs in a problem of your own or a modified SAP
    program: The source code of the program
    In the editor, choose "Utilities->More
    Utilities->Upload/Download->Download".
    4. Details about the conditions under which the error occurred or which
    actions and input led to the error.
    Source Code Extract
    Line
    SourceCde
    2708
    is_subtottxt_info = ls_subtot_info
    2709
    ip_subtot_line    = lr_data
    2710
    changing
    2711
    c_subtottxt       = l_subtottxt.
    2712
    ls_lvc_data-value = l_subtottxt.
    2713
    2714
    append ls_lvc_data to ct_lvc_data.
    2715
    endif.
    2716
    2717
    2718
    Column per Fieldcat Entry
    2719
    2720
    ls_lvc_data-value = space.
    2721
    clear ls_lvc_data-style.
    2722
    loop at it_fcat_local assigning <ls_fcat>
    2723
    where tech ne 'X' and no_out ne 'X'.
    2724
    if l_invisible eq 'X'.
    2725
    clear l_invisible.
    2726
    if <ls_fcat>-do_sum is initial.
    2727
    continue.
    2728
    else.
    2729
    clear ls_lvc_data-col_pos.
    2730
    endif.
    2731
    endif.
    2732
    2733
    add 1 to ls_lvc_data-col_pos.
    2734
    2735
    assign component <ls_fcat>-fieldname
    2736
    of structure <ls_data> to <l_field_value>.
    2737
    if sy-subrc ne 0.
    >>>>>
    message x000(0k).
    2739
    endif.
    2740
    2741
    *... work on average
    2742
    if <ls_fcat>-do_sum eq 'C'.
    2743
              Initialize average result and entries
    2744
    <l_field_value> = 0.
    2745
    clear l_entries.
    2746
    2747
              retrive unit from fieldcatalog
    2748
    assign space to <l_unit>.
    2749
    if not <ls_fcat>-cfieldname is initial.
    2750
    assign component <ls_fcat>-cfieldname
    2751
    of structure <ls_data> to <l_unit>.
    2752
    endif.
    2753
    if not <ls_fcat>-qfieldname is initial.
    2754
    assign component <ls_fcat>-qfieldname
    2755
    of structure <ls_data> to <l_unit>.
    2756
    endif.
    2757

  • SUM for a field in ALV

    Hello Guys,
    CAn any one tell me how to do the SUM for a particular column in ALV.It should display at the End of the records.The column field is TYPE N(4).
    My CODE is like this:
    CLEAR fc_tmp.
      fc_tmp-col_pos         =  5.
      fc_tmp-reptext_ddic    = 'POINTS'.
      fc_tmp-fieldname       = 'POINTS'.
      fc_tmp-tabname         = 'ITAB'.
      fc_tmp-outputlen       = 15.
      fc_tmp-key             = 'X'.
      fc_tmp-do_sum          = 'X'.
      APPEND fc_tmp TO fieldcat.
    This is not working.
    Thanks in Advance,
    Take care

    Hi,
    populate the IT_SORT internal table of REUSE_ALV_GRID_DISPLAY provided in the importing parameters.
    fieldname = Company Code
    append fieldname to it_sort.
    fieldname = division.
    append fieldname to it_sort.
    If you explicitly need subtotals then add the following line
    subtot = 'X'
    For obtaining sum you have an attribute "do_sum" in fieldcatalog , set it to 'X' and you should be able to do sum on that field.
    <b>Ensure that these should be numeric / currency or quantity datatypes only.</b>
    wa_fieldcat-datatype = 'CURR'.   or
    wa_fieldcat-datatype = 'QUAN'.
    Hope this solves your problem
    Cheers,
    Simha.
    PS : Please reward points if solution is helpful

  • How to set a default value in a DateTime field?

    Hi!, how do you set a default value in a DateTime field in a user table to the value of "today"?
    Thank you!

    It's in SAP Business One 2007, in User-Defined-Fields, under User Tables, Iam trying to add a field to a Table I created in the User-Defined-Tables-Setup menu.
    I click Add then type the field name, description and then I select the Type, which is DateTime, then the SelectDefault Value For Field get's grayed out.
    Thank you!

  • SharePoint Bug? Conflict Error when saving a Page with a "Required" DateTime field in the page layout

    Hello,
    I've just recently encountered a weird error / bug in SharePoint. Here is the scenario:
    - I have a custom column "Test Date" that is of DateTime field type. The field is configured as REQUIRED.
    - It is added to a custom Content Type "Test CT" that is based on a "Publishing Page" content type
    - I have created a Page Layout "Test PL" which is based on that particular content type.
    Now here is what happens:
    1. I try to create a page based on both that Content Type and Page Layout in the Pages Library. I manage to create it successfully.
    2. However, when I go to try and edit the page, fill-in the required values and try to save it using the PAGE TAB -> SAVE BUTTON, I get the below error/s. Note that this happens no matter what I choose in the drop-down menu for Save Button.
    "The file XXX has been modified by USER on DATE"
    But I know I am the ONLY user modifying the page. 
    If I try to save again it gives me options to whether Discard my Changes, Keep Editing, Overwrite Changes, or Merge.
    3. HOWEVER, if I use the Save button on the UPPER RIGHT corner of the screen (the shortcut). I am able to save successfully without any errors!
    The only thing I've tried that made it work was if I made the DateTime OPTIONAL. But I need it to be REQUIRED.
    Is there any workaround to this error / bug?
    Thanks

    I have some additional info but nothing really good. 
    If you click the Save in the left side of the Ribbon then it looks like that is when you get the message. If you click the Save in the top right corner you won't get the message. They must be calling different saving functions. 
    There really is no way around it other than making the field optional which probably removes some server side validation checks causing that message.
    We've chosen to remove that field from the page as I needed it required, then they can't publish the page until they go to the properties and set the article date. By removing the field from the page layout the message goes away.
    I hope MS will fix this at some point.
    -tom daly

  • Material description filled automatically as the sum of two fields

    Hello to all
    We can automate the process of the creation a new material doing that the field material description(MAKT-MAKTX) can be filled by the system before saving(not by the user) as the sum of two fields in the MARA table that the users will be filled manually.
    Is it possible using a user exit, field exit,....?
    Thanks in advance.
    Regards

    Hello to all
    We can automate the process of the creation a new material doing that the field material description(MAKT-MAKTX) can be filled by the system before saving(not by the user) as the sum of two fields in the MARA table that the users will be filled manually.
    Is it possible using a user exit, field exit,....?
    Thanks in advance.
    Regards

  • [CR integrated in VS 2005] - sum of string fields

    Hello,
    i am discovering CR,
    and i am trying to do the sum of a field (number) but declared as string. the declaration of the field cannot be changed (string in the database).
    so i want to do the sum of this field.
    i wonder if it is possible, and if yes, how.
    maybe something like a formula.
    I saw the functions: ToNumber () and Cdbl() for conversion, and Sum().
    If someone has an idea, i will be very interested.
    PS: sorry if my question is not understandable, i'm french. If you don't understand it, i would rewrite it.
    thank you!

    thank you.
    I could convert, but the problem is to make the sum of the conversion.
    i would like to do something like:
    Sum(ToNumber ()) but CR does not accept it.
    Maybe by using a variable in a formula (but i don't know where):
    shared numbervar total;
    total = total+ToNumber({MyField});
    and when printing a formula field at the bottom of the report to show the total:
    shared numbervar total;
    ToText (total);

  • DateTime Field causes dump in SOAP webservice

    We're consuming a web service written in C# (.NET 4.0) which has datetime (xsd:dateTime) fields. The ABAP proxy class dumps when the service response is returned with:
    CX_SY_CONVERSION_NO_DATE_TIME:XSLT exception.An error occurred when deserializing in the simple transformation program /1SAI/TXS72F7E0958348097F34D9.Value 2011-12-15T00:00:00 is not a valid date with time in accordance with the XML format for ABAP
    Apparently SAP expects 2011-12-15T00:00:00Z but we are getting 2011-12-15T00:00:00 (without the Z). What does this mean and how can we fix it? Our .NET developer apparently has no control over the "Z" and this all seems a bit of strange reason to dump.
    Here is the partial SOAP response:
    <Expires>2011-07-18T00:00:00</Expires>
    Here is the relevant WSDL:
    <xsd:element minOccurs="0" name="expires" type="xsd:dateTime" />

    ping

  • Accessing data in a MS Access DATETIME field

    Can anybody please tell me how to retrieve and update data in a DATETIME field from a table in MS Access Database? (I have a JDBC connection and can query/update other fields, but not this one)
    thx

    For retrieving, use rs.getString("FIELD_NAME") or rs.getString(COLUMN_NO) method. For updating and/or inserting, use single quots('...') and proper datetime format.

  • Datetime field overflow / String data right truncation

    Hi All,
    Getting the follwing erros while working with timestamp for selecting from or inserting data into DB2 through WebSphere 6.1.
    I am passing values like this: 2006-05-02-21.57.26.744341.
    The queries run fine while executing through some SQL Frontend editor.
    [IBM][CLI Driver] CLI0114E Datetime field overflow. SQLSTATE=22008
    [IBM][CLI Driver] CLI0109E String data right truncation. SQLSTATE=22001
    Please let me know the problem.

    If you are trying to convert to a java.sql.Timestamp as part off the process of inserting into DB2 then Timestamp is derived from java.util.Date which holds the time in milli-seconds but you are providing a microseconds field.
    Could this be the problem?

  • Full load failed with  [Microsoft][ODBC SQL Server Driver]Datetime field

    Hi,
    we are doing a full load with RDBMS SQLServer.
    It failed due to the below error.
    [Microsoft][ODBC SQL Server Driver]Datetime field overflow. Can you please help
    thank you

    968651 wrote:
    Hi,
    we are doing a full load with RDBMS SQLServer.
    It failed due to the below error.
    [Microsoft][ODBC SQL Server Driver]Datetime field overflow. Can you please help
    thank youhttp://bit.ly/XUL950
    Thanks,
    Hussein

  • How to calculate sum of the fields in adobeforms

    Hello Experts
    can  i know how to calculate sum of fields in the adobe form.  I have few fields to be summed in total field.
    Regards

    Hello Surendra,
         Suppose you are having 4 fields and the 4th field is the TOTAL field.
         Write the below Javascript on the Initialize event of TOTAL field as shown below.
    Remember that if you use just "+" sign without Number() or ParseInt() function it acts like String Concatenation.
    this.rawvalue = Number( this.parent.field1.rawvalue ) +
                          Number( this.parent.field2.rawvalue ) +
                          Number( this.parent.field3.rawvalue ) ;
    You can also write is as shown below.
    this.rawvalue = parseInt( this.parent.field1.rawvalue ) +
                             parseInt( this.parent.field2.rawvalue ) +
                             parseInt( this.parent.field3.rawvalue ) ;

  • AppServ Control keeps mangling dateTime fields in WS tests

    I've deployed a web service that takes 2 dateTime fields as parameters. The format of the dateTime fields is xsd:dateTime (YYYY-MM-DDTHH:mm:ss.SSS).
    However, every time I type in a value in the datTime form field, and press the Invoke button, the AS Control mangles the date into a weird format like YYYY-MM-DDTHH:mm:ss.SSS+X.XXX, and the invoke fails with the error message 'Not all form values are valid."
    How do I bypass this bug? Without it, I can't test the web service using the AS Control.

    I'm testing a web service using the ASC.
    The ASC automatically creates a web page with a form in it to enter my test data.
    For a dateTime field, the "helpful" text next to the field's edit box says "xsd:dateTime (YYYY-MM-DDTHH:mm:ss.SSS)"
    So I type in 2007-07-10T23:12:10.000.
    Until this point, the color of the text in the field is "black" to indicate that the syntax is okay.
    I then change focus so that my cursor is in the next field. Or I press the Invoke button... same thing.
    The contents of the dateTime field automatically change to:
    2007-07-10T23:12:10.000-08.0:00
    and the color of the text in the field turns to "red" to indicate that the syntax is bad. And below the Invoke button I see a message that says:
    "Not all form values are valid."
    I try to change the value back to what it was, but the ASC insists on changing it back to the bad value each time I press Invoke or shift focus away from the dateTime field.

  • Getting a null when trying to access DateTime fields (that I've added) from my work item

    I'm getting a null when trying to access (custom) DateTime fields from my work item.
    I've got a customized work item with 'extra' string and datetime fields.
    <FieldDefinition name="Design Version" refname="XXX.DesignVersion" type="String" reportable="dimension" />
    <FieldDefinition name="Date Closed" refname="XXX.DateClosed" type="DateTime" reportable="dimension" />
    This code fails:
    WorkItem workItem = workItemStore.GetWorkItem(workItemId);
    var tt1 = workItem["XXX.DesignVersion"];//works
    var tt3 = workItem["XXX.DateClosed"]; //tt3 == null, fails also for html fields
    Any idea what's up? thanks

    Hi TimB,  
    Thanks for your post.
    What’s the version of your TFS?
    If you open this work item in VS, there’s no date value in your Date Closed field? Please try below code snippet:
    if (wr.Fields["XXX.DateClosed"].Value
    == null)
    Console.WriteLine(wr.Fields["XXX.DateClosed"].Value);
    else
    Console.WriteLine(wr.Fields["XXX.DateClosed"].Value);
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

Maybe you are looking for

  • Creation of a complex object from several databases?

    Hello! We need to have an ability to change certain property of the record, stored in the database, without reading the full record from the database, changing the property and updating the database with this new record. As far as I know there's no w

  • Flicker when filming an LCD screen

    I am filming an LCD screen that is set to 60hz. The camera I use shoots in 60i When I import into PP CS5, The video flickers from missing information I'm guessing. My project settings reflect 29.97 drop-frame. Do I need to make it non-drop frame? Tha

  • TS1702 Deleting unwanted apps

    How can I delete unused apps from my iPhone and iPad that do not show up on iTunes but still show on the devices when I pull up the "purchase history"   I have deleted the iCloud, synced both devices etc. I have hidden them but do they still take up

  • Specs of the Topseller T61p 6460D. ?

    Hi, Does anyone know the specs of this type T61p since the D. version doesn't exist on the topseller program catalog list. What is the difference with the 6460DVU, it's priced the same as the D. ( http://www.sparco.com/cgi-bin/wfind2?spn=A73Q506 ) an

  • Tables in MRP list??

    Hi Experts, I need help to identify the tables from which the data is fetched when we run the MRP list transaction (MD05). I need the tables from which the 'Request/Scheduled Qty' and 'Request scheduled date' are fetched. My assumption is that the ot