简体   繁体   English

使用SQL聚合多个列上的正值

[英]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: 在此示例中,如果我想对3列中的值求和,我想得到以下结果:
Column1: (3+2)=5, Column2(5+4)=9 and Column3(6+3)=9. 列1:(3 + 2)= 5,列2(5 + 4)= 9,列3(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? 因此,我的问题是使用单个SQL查询是否可能实现此操作,或者我将不得不创建临时表?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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