简体   繁体   中英

Aggregating positive values on multiple columns with SQL

I am trying to do aggregation functions on a specific database table with multiple columns. For example:

Sample Table ID Column1 Column2 Column3 1 3 5 -2 2 -1 4 6 3 2 -1 3

In this example, if I would like to sum the values in the 3 columns, I want to get the following result:
Column1: (3+2)=5, Column2(5+4)=9 and Column3(6+3)=9.
Thus, my question is whether this is possible with a single SQL query or I would have to go through creating temporary tables?

Note: The data set is big.

If I understand correctly, you only want to SUM the positive values, and ignore the negatives? If so try:

SELECT 
    SUM(CASE WHEN Column1 > 0 THEN Column1 ELSE 0 END) AS 'Column1PosTotal',
    SUM(CASE WHEN Column2 > 0 THEN Column2 ELSE 0 END) AS 'Column2PosTotal',
    SUM(CASE WHEN Column3 > 0 THEN Column3 ELSE 0 END) AS 'Column3PosTotal'
FROM Table

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