Created
April 25, 2015 07:10
-
-
Save ibejoeb/df57cb34bbe609293d6e to your computer and use it in GitHub Desktop.
Solving Cheryl's Birthday in SQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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