Results 1 to 17 of 17

Thread: Get SUM of a field on a different table

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Mar 2007
    Posts
    124

    Get SUM of a field on a different table

    Hello!

    I am using SQL Server 2000. I have two tables. The first table is the list of employees (EMP_ID, firstname, lastname, etc). The second table is their production everyday( ID , WORDCOUNT, LINECOUNT, DURATION, etc)

    wordcount and linecount are numbers while duration is hr:mm:ss

    EMP_ID is the same with ID. Primary and foreign key.

    I have a question. What is the proper SQL for getting the total sum of wordcount, linecount and duration from the other table.

    I know the SUM() function of SQL and the Inner Join but i dont know how to combine them.

    My desired output is the Employee's list (no duplicate) from table one plus the total sum of the three field from the other table.

    TIA.

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Get SUM of a field on a different table

    The fact that there is a Join involved is actually irrelevant to what you want to achieve - it would be done the same way if there was a Join or not.

    What you need is a Group By clause, which tells the database system to 'merge' rows with identical values for those fields. In this case you want it for the Employee fields, so would add all of those to the Group By, eg:
    Code:
    SELECT EMP_ID, firstname, lastname, ...
    FROM ...
    WHERE ...
    GROUP BY EMP_ID, firstname, lastname, etc
    You also need to tell it how to merge the values in the other fields, which you do with functions like Sum in the Select clause, eg:
    Code:
    SELECT EMP_ID, firstname, lastname, Sum(WORDCOUNT), Sum(LINECOUNT), Sum(DURATION)
    FROM ...
    WHERE ...
    GROUP BY EMP_ID, firstname, lastname, etc
    This needs to be done for every field in the Select clause that is not in the Group By clause.

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Mar 2007
    Posts
    124

    Re: Get SUM of a field on a different table

    Sorry i got confused. What is my final SQL statement?

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Mar 2007
    Posts
    124

    Re: Get SUM of a field on a different table

    Ok i tried the group by but it's not what i want to achieve. The first name and last name from the first table has duplicates.

    My expected output should be one table with no duplicate of names but the other fields has summed up.

    EMP_ID| Firstname | Lastname|Total SUM of Wordcount from 2nd table|Total SUM of Linecount from 2nd table|


    My 2nd table looked like this

    ID | Wordcount | Linecount |
    ---------------------------
    1 |
    2 |
    1 |
    1 |
    3 |
    3 |

    The ID has duplicates here. I want to get the SUM as one and place it as a single field on the expected output.

  5. #5
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Get SUM of a field on a different table

    What is considered unique is the combination of values of all fields listed in the Group By clause. If you only want Firstname and Lastname to be used for that, only include those in the Group By clause (ie: remove Emp_ID).

    If you don't want/need Emp_ID in your final output, simply remove it from the Select clause too. If you do need it, you will need to do something else (perhaps use a function, like Sum) to get the value you want from it.

  6. #6
    Addicted Member
    Join Date
    Dec 2006
    Location
    Between Try & Catch
    Posts
    249

    Re: Get SUM of a field on a different table

    Please tell me "ID" is not a primary key.
    If my post helped you, please rate it!

    Languages: VB/ASP.NET 2005, C# 2008,VB6
    Databases: Oracle (knowledge not currently in use), DB2

    FROM Customers
    WHERE We_Know_What_We_Want <> DB.Null
    SELECT *
    0 rows returned

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Mar 2007
    Posts
    124

    Re: Get SUM of a field on a different table

    Quote Originally Posted by si_the_geek
    What is considered unique is the combination of values of all fields listed in the Group By clause. If you only want Firstname and Lastname to be used for that, only include those in the Group By clause (ie: remove Emp_ID).

    If you don't want/need Emp_ID in your final output, simply remove it from the Select clause too. If you do need it, you will need to do something else (perhaps use a function, like Sum) to get the value you want from it.

    How about JOIN? I am using two tables. In your example i didn't see any JOIN syntax used.

  8. #8

    Thread Starter
    Lively Member
    Join Date
    Mar 2007
    Posts
    124

    Re: Get SUM of a field on a different table

    Quote Originally Posted by Blakk_Majik
    Please tell me "ID" is not a primary key.
    It is not a primary key coz it has duplicates. It is a foreign key to EMP_ID and EMP_ID is a primary key to table 1.

  9. #9
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Get SUM of a field on a different table

    Like I said before, the Join is irrelevant to this (it would be included in the FROM and/or WHERE clauses as you usually do it). I didn't show an example, as you said you know how to do that part.


    If it still isn't giving the results you want, show us the current SQL statement, and some the data it returns (along with an explanation of why that data isn't what you want).

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Mar 2007
    Posts
    124

    Re: Get SUM of a field on a different table

    Thanks SI i got it sorted out. However i got one problem summing the duration coz the format is hh:mm:ss. It's returning an err.

    Current SQL statement. Wordcount and linecount is summing up.

    Code:
    SELECT     TABLE1.EMP_ID, TABLE1.EMP_LASTNAME, TABLE1.EMP_FIRSTNAME, TABLE1.EMP_MIDDLE, 
                          SUM(TABLE2.WORDCOUNT) AS Expr1, SUM(TABLE2.LINECOUNT) AS Expr2
    FROM         TABLE1 INNER JOIN
                          TABLE2 ON TABLE1.EMP_ID = TABLE2.ID
    GROUP BY TABLE1.EMP_ID, TABLE1.EMP_LASTNAME, TABLE1.EMP_FIRSTNAME, TABLE1.EMP_MIDDLE
    How do i sum up durations?

  11. #11
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Get SUM of a field on a different table

    Telling us that there was an error isn't much use by itself.. which error was it?

    What is the data type of the field?

  12. #12

    Thread Starter
    Lively Member
    Join Date
    Mar 2007
    Posts
    124

    Re: Get SUM of a field on a different table

    It is default as nvarchar. I honestly don't know what datatype to use. There's nothing much that fit into that category.

    It cant be date/time coz its a duration.

  13. #13
    Code Monkey wild_bill's Avatar
    Join Date
    Mar 2005
    Location
    Montana
    Posts
    2,993

    Re: Get SUM of a field on a different table

    What I would do is substring the data out, then convert it to its equivilent in seconds, so you can use the sum functionality, then you could convert it back if you wanted.

  14. #14
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Get SUM of a field on a different table

    A duration is a measure of time, and as such it could be stored as a Date/Time.

    Doing that will mean that a Sum will work as expected, except in the case where the total goes beyond 24 hours, which would take a bit of effort to fix (perhaps as much as wild_bill's suggestion).


    edit: An alternative, that is likely to be better, would be an extension of what wild_bill suggested - which would be to store it as a number of seconds (in a numeric data type). This would allow Sum, and would be relatively simple to convert to the format "hh:nn:ss".

  15. #15

    Thread Starter
    Lively Member
    Join Date
    Mar 2007
    Posts
    124

    Re: Get SUM of a field on a different table

    Yeah that could be it. But I already started the database with 30k records ouch!

    I can't redo this. I was hoping i could do it with pure SQL but it seems like it's either i hard code a loop or change my database.

    Anyway, last question, is there any chance i could work around with pure SQL?

  16. #16
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Get SUM of a field on a different table

    You can do it with SQL, using SubString as wild_bill mentioned (to separate the string into the H/N/S parts), along with Cast to convert the strings to numeric, and then mathematical operators to get them to a total number of seconds.

    That will end up looking something like this (untested):
    Code:
    Sum(
      Cast( SubString(Duration, 1, 2)  as Integer) * 3600 +
      Cast( SubString(Duration, 4, 2)  as Integer) * 60
      Cast( SubString(Duration, 7, 2)  as Integer)
    )
    ..which will return the total number of seconds.


    Converting it to the format you presumably want (HH:NN:SS) is easy enough, but it would be very long-winded to do it inline with the other work.

    What I recommend is to create a function in the database to do it, something like this (again untested I'm afraid):
    Code:
    CREATE FUNCTION Seconds_to_HMS
    (
      @NumberOfSeconds AS Integer
    )
    RETURNS VarChar
    BEGIN 
      RETURN Cast(@NumberOfSeconds /3600 as VarChar) + ':' + Right('0' + Cast((@NumberOfSeconds  / 60) % 60 as VarChar), 2) + ':' + Right('0' + Cast(@NumberOfSeconds % 60 as VarChar), 2);
    END
    You can then add a call to that around the previous work, eg:
    Code:
    Seconds_to_HMS(
    Sum(
      Cast( SubString(Duration, 1, 2) as Integer) * 3600 +
      Cast( SubString(Duration, 4, 2) as Integer) * 60
      Cast( SubString(Duration, 7, 2) as Integer)
    )
    )

  17. #17

    Thread Starter
    Lively Member
    Join Date
    Mar 2007
    Posts
    124

    Re: Get SUM of a field on a different table

    Hey thanks Si. Let me try that. You are God send. + rep

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width