How to find out if all cells have the same value in a certain column

How to find out if all cells have the same value in a certain column (name changed)

I want to have some scalar value that tells me that all values ​​in the column are equal:

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

UPDATE

Now I realized that I really do not need TrueForAll, I need to make sure that all the values ​​in the column are equal, for example, I want to know if all the Group.Items elements have the same prices.

+5
source share
5 answers

For your updated requirement, something like this will look the way 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

1, ( , )

+4

?

select count( distinct price) from table

1, ...

where price is not null

+13

Maybe this?

DECLARE @bit bit
if exists(SELECT Name FROM Contact WHERE Name IS NULL) 
   SET @bit = 0
ELSE
  SET @bit = 1
+1
source

Not very good for NULL, but 2008 can do:

SELECT 1 WHERE 'Blue' = ALL ( SELECT Color FROM dbo.Hat )

OR

DECLARE @bit bit

SET @bit = 
CASE ( SELECT 1 WHERE 'Blue' = ALL ( SELECT Color FROM dbo.Hat ))
WHEN 1 THEN 1 ELSE 0 END 

UPDATE

All colors

SET @bit = 
CASE(
   SELECT 1 WHERE
  (SELECT TOP(1) Color FROM dbo.Hat) = ALL ( SELECT Color FROM dbo.Hat )
    )
WHEN 1 THEN 1 ELSE 0 END 
+1
source

This solves your first question:

SELECT
    CASE
        WHEN EXISTS(
            SELECT 1
            FROM Contact
            WHERE Name IS NULL
        ) THEN 0
        ELSE 1
    END

ADDED:

This will solve your second:

SELECT
    CASE
        WHEN EXISTS(
            SELECT TOP 1 1 FROM (
                SELECT
                    ItemGroupName,
                    COUNT(Price) AS CNT
                FROM ItemGroup
                GROUP BY ItemGroupName
                HAVING COUNT(Price) > 1
            ) t
        ) THEN 0
        ELSE 1
    END

By the way, when you use the exist function, its SELECT 1 (constant) is better, so less data is returned

0
source

All Articles