@shiro_ Why not save your month column to a proper date format? Like 2022-01-01 (January) 2022-02-01 (Feb) and so on. So you could easily sort data
Laravel Postgres Formatted Date Month Year Error Ordering Dates
I have a database that looks like this :
sum | status | failure_reason | month | created_at
1.2 | Failed | AbsentSubscriber | JANUARY -2022 | 2022-01-17
I want to make a graph of total costs across a specified period based on different statuses. My query is returning month/year and the total cost at that time.
Despite using order by to display data in an ascending order, my graph is quite unordered. This is how my query looks :
$delivery_failure = DB::table('partners_sms')->select(DB::raw('month, sum(sum) as y'))
->whereBetween('created_at', [new Carbon($start_date), new Carbon($end_date)])
->where('failure_reason', '=', 'DeliveryFailure')
->groupBy('month')
->orderBy('month', 'DESC')
->get();
I have also tried this approach with no luck:
$successNonPartner = SMSData::query()->selectRaw("to_char(created_at::timestamp, 'MONTH-YYYY') as month")
->whereBetween('created_at', [new Carbon($start_date), new Carbon($end_date)])
->where('status', '=', 'Success')
->groupBy('created_at')
->orderBy('created_at', 'DESC')
->get();
Any advise or recommendations on an ideal approach to format my date in month/year and order the dates will be appreciated. I am using laravel and postgres.
@shiro_ you can do so using to_char(timestamp, 'month YYYY') as monthYear in your select.
I think it's problematic saving your date as string (January 2022) and converting it back to real dates as opposed to real dates first then converting to whatever you need.
Please or to participate in this conversation.