Search code examples
sqlsnowflake-cloud-data-platformcasewindow-functionssnowflake-schema

return 1 when multiple conditions meet


I have a table that looks like this:

ACCOUNT       hour_count
A             24
B             24
C             23
D             22

I want to create an sql statement that just returns "1" when ALL conditions meet:

when account is A, hour_count = 24
when account is B, hour_count = 24
when account is C, hour_count > 22
when account is D, hour_count > 22

How can I achieve this?

I tried using a CASE statement, but i couldn if 't figure out how to include multiple conditions. It wouldn't work with an AND within a single WHEN statement:

SELECT
CASE
    WHEN ((ACCOUNT = 'A' AND hour_count = 24) )
    THEN 1
END
FROM hour_counts

Solution

  • if you only a single 1 returned if all of the conditions met else nothing returned

    with cte as (
    select case
              when account in (‘A’,’B’) and hour_count = 24) then 1 
              when account in (‘C’,’D’) and hour_count > 22) then 1
           end as c_count
      from hour_count)
    select 1 as one       
      from cte
    having sum(c_count)=4 —- if all conditions met