Search code examples
sqlsql-servert-sqlconditional-statementsequivalent

How to know if all the cells have the same value in some column


How to know if all the cells have the same value in some column (title changed)

I want to have a bit scalar value that tells me if all the values in a column equal something:

DECLARE @bit bit
SELECT @bit = TRUEFORALL(Name IS NOT NULL) FROM Contact

UPDATE

I now realized that I actually don't need the TrueForAll, what I do need is to make sure, that all values in a column are equal, for example, I want to know whether all Group.Items have the same price.


Solution

  • For your updated requirement something like this would appear to do what you want:

    DECLARE @IsSameGroup bit
    SELECT @IsSameGroup = CASE WHEN COUNT(*) > 1 THEN 0 ELSE 1 END
    FROM (SELECT Name FROM Contact GROUP BY Name) groups
    

    When the count is greater the 1 you have two different names (or prices depending on what you group on)