简体   繁体   中英

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 :-)

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>

try this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM