Search code examples
sqlloopsforeach

Filter sets by a boolean column


I have a list of customers and there are many duplicates. To solve this problem the business is setting one of them as primary. The process has not been followed; I need to find all the customers that don't have a primary key. The customers' legal_name values all match, and the is_primary field is Boolean. How can I do this?

I have sorted and organized the list but can not figure out how to check for each customer if is there a primary set.

select distinct customer_id, 
       COUNT(customer_id) as C, 
       is_primary from customer_table
where  is_primary = false
group by customer_id, is_primary 
order by C ASC

Solution

  • Took your query and altered it using a HAVING clause (see details here)

    SELECT
        customer_id, 
        COUNT(CASE WHEN is_primary THEN 1 ELSE NULL END) as C
    from customer_table 
    group by customer_id
    having COUNT(CASE WHEN is_primary THEN 1 ELSE NULL END) = 0