Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Laylow
Starting Member
14 Posts |
Posted - 2011-02-02 : 09:35:46
|
| Hi All,I have a problem writing a query to sum 'AMOUNT' on distinct code e.g. CABE01P001 for all type e.g. 'ALP' and 'ARE'.This is the script I have currently:SELECT CODE,SUM (AMOUNT) AS AMOUNT,TYPEFROM TABLEWHERE (CODE) LIKE 'C_____P___'GROUP BY CODEBelow is the Raw data and the Result I would like to see.So for CABE01P001, ALP, I should have a total of 10924.95 as shownin the result table below.RegardsLaylowRAW DATA CODE______ TYPE AMOUNTCABE01P001 ALP 5349.9CABE01P001 ALP 5575.05CABE01P001 ARE -5575.05CABE01P001 ARE -5349.9CABE01P002 ALP 1290CABE01P002 ALP 4230CABE01P002 ARE -4230CABE01P002 ARE -1290CABE01P003 ALP 170CABE01P003 ALP 423CABE01P003 ARE -423CABE01P003 ARE -170 RESULT CODE_____ TYPE AMOUNTCABE01P001 ALP 10924.95CABE01P001 ARE -10924.95CABE01P002 ALP 5520CABE01P002 ARE -5520CABE01P003 ALP 593CABE01P003 ARE -593 |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2011-02-02 : 09:41:59
|
| Add TYPE to the GROUP BY clause. |
 |
|
|
Laylow
Starting Member
14 Posts |
Posted - 2011-02-02 : 09:55:11
|
quote: Originally posted by robvolk Add TYPE to the GROUP BY clause.
Hi Robvolk,Slight problem with doing it that way is that I get figures which are wrong. I already tried that method and I was getting for example 16,500 for CABE01P001 when it should be 10,924.95Would you know of a better approach?CheersLaylow |
 |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2011-02-02 : 10:13:59
|
| The only way you'd get 16,500 is if you had additional rows for that CODE and TYPE combination. Can you add a COUNT(*) to your query and see if it shows more than 2 rows? |
 |
|
|
Laylow
Starting Member
14 Posts |
Posted - 2011-02-02 : 10:24:43
|
quote: Originally posted by robvolk The only way you'd get 16,500 is if you had additional rows for that CODE and TYPE combination. Can you add a COUNT(*) to your query and see if it shows more than 2 rows?
Hi Robvolk,Thanks for this, yes you are right there was a hidden row I didn't see.RegardsLaylow |
 |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2011-02-02 : 10:25:59
|
Those sneaky hidden rows! |
 |
|
|
|
|
|
|
|