Oeyvind
Oeyvind

Reputation: 357

Sum certain columns in MS SQL-query

I have a database with accounts, and need to make additions to certain columns:

Customer | Account | DateStatement | Risk | Balance
123      | 456     | 201606        | Low  | 1000
123      | 645     | 201606        | Low  | 500
321      | 852     | 201606        | High | 1500

One customer may one or many accounts, and I need the total of the costomers balance for all accounts. Obviously date and risk is the same for each customer, and cannot be added.

The table has thousands of customers, and there are about 50 columns, whereas about 20 needs to be added, while the other 30 should be shown only once. I need the result to show one line per customer, such as

Customer | DateStatement | Risk | Balance
123      | 201606        | Low  | 1500
321      | 201606        | High | 1500 

How can I do this the simplest way, considering I have to add about 20 columns? Subqueries seems very complex, if I need that many?

--

Thanks guys. It was really so simple as you suggested. I had missunderstood how GROUP BY worked. It works like a charm based on your answers :-)

Upvotes: 0

Views: 547

Answers (2)

Kishore
Kishore

Reputation: 16

try this.

SELECT customer,DateStatement ,Risk ,sum(Balance) 
FROM table_name
GROUP BY customer,DateStatement ,Risk

Upvotes: 0

Jonathan Shields
Jonathan Shields

Reputation: 120

If I understand correctly, its just a group by

SELECT Customer,DateStatement,Risk,<other columns>,SUM(Balance),..SUM(OtherColumn) etc
FROM sometable
GROUP BY Customer,DateStatement,Risk,<other columns>

Upvotes: 2

Related Questions