Skip to content

Instantly share code, notes, and snippets.

@ibejoeb
Created April 25, 2015 07:10
Show Gist options
  • Save ibejoeb/df57cb34bbe609293d6e to your computer and use it in GitHub Desktop.
Save ibejoeb/df57cb34bbe609293d6e to your computer and use it in GitHub Desktop.
Solving Cheryl's Birthday in SQL
create table bdays (m, d) as
values
('May', 15), ('May', 16), ('May', 19),
('June', 17), ('June', 18),
('July', 14), ('July', 16),
('August', 14), ('August', 15), ('August', 17)
;
with x as (
select
m,
(count(*) over (partition by d) = 1) as m_decides
from bdays
),
s1 as (
select
m,
not(bool_or(m_decides)) as s1
from x
group by m
),
s2 as (
select
bdays.*,
s1,
(count(*) over (partition by s1, bdays.d) = 1) as s2
from
bdays
inner join s1 on s1.m = bdays.m
),
s3 as (
select
s2.*,
(count(*) over (partition by s1, s2, m) = 1) as s3
from s2
)
select *
from s3
where s1 and s2 and s3
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment