I have been stuck with this issue for hours now.
I have a table called subscribe with the following fields
- id (int)
- sub_type (week, month, year) (Varchar)
- sub_duration (int)
- last_renewal (Date)
I want to merge the sub_duration and sub_type and add it to the last_renewal (to get the expiring date), Then check if the result is greater/lesser than the current date. Below is what I have done.
SELECT s.*
FROM subscription s
WHERE (SELECT DATE_ADD(s.last_renewal, INTERVAL (CONCAT(s.sub_duration), ' ', s.sub_type)))< CURDATE()
CodePudding user response:
You can combine CASE
with DATE_SUB
to get the expiration date in a subquery. Then it's easy to compare and analyze each case.
For example:
select *,
case when expiring_date < curdate() then 'Expired'
when expiring_date > curdate() then 'Active'
else 'Expires Today'
end as status
from (
select *,
case when sub_type = 'week' then date_add(last_renewal, interval sub_duration week)
when sub_type = 'month' then date_add(last_renewal, interval sub_duration month)
when sub_type = 'year' then date_add(last_renewal, interval sub_duration year)
end as expiring_date
from subscription
) x
Result:
id sub_type sub_duration last_renewal expiring_date status
--- --------- ------------- ------------- -------------- -------
1 month 2 2021-04-12 2021-06-12 Expired
2 week 1 2021-07-11 2021-07-18 Expired
3 week 4 2021-11-11 2021-12-09 Active
See running example at DB Fiddle.
CodePudding user response:
INTERVAL accepts keywords, not strings
you can use case when
The key part of sql is like this
select *
from (
select 'week' sub_type, 1 sub_duration union all
select 'year' sub_type, 1 sub_duration) s
where case when s.sub_type = 'week'
then DATE_ADD(now(), INTERVAL s.sub_duration week)
when s.sub_type = 'month'
then DATE_ADD(now(), INTERVAL s.sub_duration month)
when s.sub_type = 'year'
then DATE_ADD(now(), INTERVAL s.sub_duration year)
end > now()