Home > OS >  How to check unique values in SQL
How to check unique values in SQL

Time:10-26

I have a table named Bank that contains a Bank_Values column. I need a calculated Bank_Value_Unique column to shows whether each Bank_Value exists somewhere else in the table (i.e. whether its count is greater than 1).

I prepared this query, but it does not work. Could anyone help me with this and/or modify this query?

SELECT 
    CASE 
        WHEN NULLIF(LTRIM(RTRIM(Bank_Value)), '') = 
            (SELECT Bank_Value
            FROM [Bank] 
            GROUP BY Bank_Value
            HAVING COUNT(*) = 1) 
        THEN '0' ELSE '1' 
    END AS Bank_Key_Unique
FROM [Bank]

CodePudding user response:

A windowed count should work:

SELECT
    *,
    CASE 
        COUNT(*) OVER (PARTITION BY Bank_Value)
        WHEN 1 THEN 1 ELSE 0
    END AS Bank_Value_Unique
FROM
    Bank
;

CodePudding user response:

It works also, but I found solution also:

select CASE WHEN NULLIF(LTRIM(RTRIM(Bank_Value)),'') = (select Bank_Value from Bank group by Bank_Value having (count(distinct Bank_Value) > 2 )) THEN '1' ELSE '0' END AS Bank_Value_Uniquness from Bank

It was missing "distinct" in having part.

I'm new here. Sorry that I do not know how to properly modify my result to be easily readable.

  • Related