Home > Net >  Can I search a mySQL database with multiple date ranges and give them aliases to report against the
Can I search a mySQL database with multiple date ranges and give them aliases to report against the

Time:11-29

Is it possible to search a database with a query with multiple date ranges? I need to attach an alias to each date range to report off the results. Rather than a calendar year for filtering I want to filter of the company's fiscal year.

For example,

Select * FROM <Table Name> 
WHERE <Date Field> is BETWEEN '01-05-2022' and '29-05-22' AS "May 22" 
AND WHERE <Date Field> is BETWEEN '30-05-2022' and '26-06-22' AS "Jun 22" 
AND WHERE <Date Field> is BETWEEN '27-06-2022' and '31-07-22' AS "July 22"

CodePudding user response:

I don't think assigning aliases in the WHERE clause is possible.

But something like this should work:

select
    *,
    case
        when DateColumn between '2022-05-01' and '2022-05-29' then 'May 22'
        when DateColumn between '2022-05-30' and '2022-06-26' then 'Jun 22'
        when DateColumn between '2022-06-27' and '2022-07-31' then 'Jul 22'
    end as DateRange
from
    TableName
where
    DateColumn between '2022-05-01' and '2022-05-29'
    or DateColumn between '2022-05-30' and '2022-06-26'
    or DateColumn between '2022-06-27' and '2022-07-31'
;

Note that the way you express dates is ambiguous.

  • Related