Results 1 to 2 of 2

Thread: SUM only some values

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2010
    Posts
    350

    SUM only some values

    I have a table with name, date, hours & code - for example:
    Alan,01/01/12,8,A80
    Alan,02/01/12,8,A80
    Bob,01/01/12,8,B80
    Bob,02/01/12,8,B80
    Bob,03/01/12,8,B81
    I want to get the totals for each person categorised by the last two characters of the code:
    Name,Total 80, Total 81 - giving:
    Alan,16,0
    Bob,16,8

    I can easily get the SUM for each name, but I don't know how to break it down by the code.
    Any suggestions?
    Thanks

  2. #2
    Super Moderator FunkyDexter's Avatar
    Join Date
    Apr 2005
    Location
    An obscure body in the SK system. The inhabitants call it Earth
    Posts
    7,957

    Re: SUM only some values

    Normally you wouldn't retrieve the data in that layout. You'd retrieve it something like this:-
    Name, CodeSuffix, Total
    Alan, 80, 16
    Bob, 80, 16
    Bob, 81, 8

    To do that you simply group by Name and CodeSuffix:-
    Select Name, Right(Code, 2), Sum(Hours)
    Group By Name, Right(Code, 2)

    I'd normally recommend "flipping" the columns on the client side, whether that be a report or an app. But if you really want to flip it before you return the data you'll need to use a PIVOT. Different DBs have a different syntax for this but a quick google should find you the syntax for all the major DBs.
    Last edited by FunkyDexter; Aug 7th, 2012 at 09:58 AM.
    The best argument against democracy is a five minute conversation with the average voter - Winston Churchill

    Hadoop actually sounds more like the way they greet each other in Yorkshire - Inferrd

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