create or replace function last_date (integer) returns date as
$$
select (to_date($1, 'YYYYMM') + interval '1 month' - interval '1 day')::date;
$$ language sql;
prepare get_birthday (integer) as
(
select * from member
where (birth_md between
to_char(last_date($1), 'MM01')
and to_char(last_date($1), 'MMDD')
and solar = true
)
or case when
(select lunar_md from lunar
where solars = ($1 || '01')::int
and yun = false
)
>
(select lunar_md from lunar
where solars = to_char(last_date($1), 'YYYYMMDD')::int
and yun = false
)
then (
(birth_md between
(select lunar_md from lunar
where solars = ($1 || '01')::int
and yun = false
)
and '1231'
)
or
(birth_md between
'0101'
and (select lunar_md from lunar
where solars = to_char(last_date($1), 'YYYYMMDD')::int
and yun = false
)
)
and solar = false
)
else
(birth_md between
(select lunar_md from lunar
where solars = ($1 || '01')::int
and yun = false
)
and (select lunar_md from lunar
where solars = to_char(last_date($1), 'YYYYMMDD')::int
and yun = false
)
and solar = false
)
end
order by user_id
);