-
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
-
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.