简体   繁体   English

如果条件匹配,则SQL查询以查找列中字段的总和,否则返回默认值

[英]SQL query to find the sum of fields in a column if a condition matches else return a default value

I need a SQL query for the below scenario 我需要以下情况的SQL查询

House| SquareFoot| Color

House1  10        White
House2  20        White

The query should give a sum of SquareFoot(30) only if all the values in Color field are the same. 仅当“颜色”字段中的所有值都相同时,查询才应给出SquareFoot(30)的总和。 Else it should return (0) for the below scenario 否则,在以下情况下,它应返回(0)

House| SquareFoot| Color

House1  10        White
House2  20        Red

Please let me know the best way this can be achieved through SQL 请让我知道可以通过SQL实现的最佳方法

You seem to want: 您似乎想要:

SELECT (CASE WHEN MIN(Color) = MAX(Color)
             THEN SUM(SquareFoot)
             ELSE 0
        END) as return_value
FROM t;

在这里,首先我们将从计数中检查是否非重复值= 1,然后总计将为sum(SquareFoot),或者如果非重复计数不为= 1,则总计将为0

select iif((select COUNT(distinct(Color)) from tblName) = 1, sum(SquareFoot), 0) as Total from tblName

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

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