Results 1 to 2 of 2

Thread: SUM only some values

  1. #1
    Hyperactive Member
    Join Date
    Apr 10
    Posts
    298

    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
    Hirsute Mumbler FunkyDexter's Avatar
    Join Date
    Apr 05
    Location
    An obscure body in the SK system. The inhabitants call it Earth
    Posts
    2,425

    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.
    When one of my minions says, "Hey, he's just one guy, what can he do?" I say "This"... and shoot them.

    The problem with putting your lair in a volcano is keeping your robot army from melting.

    I know that the human being and the fish can coexist peacefully - George Bush

Posting Permissions

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