简体   繁体   中英

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

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. Else it should return (0) for the below scenario

House| SquareFoot| Color

House1  10        White
House2  20        Red

Please let me know the best way this can be achieved through 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

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