Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to correctly use CASE WHEN with laravel Eloquent?

i want to display call and chat seconds and i need to group the data without repeating session_id
and for this I am using CASE WHEN designating that if type = "chat" it shows me only the chat ones and type = "call" only the call ones

but the problem is that the WHEN CASE only shows me the type of chat and adding null value to the call.

my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$sub = DB::table('session_details')
    ->select('session_id',
    DB::raw('CASE WHEN type = "chat" THEN time_in_secs END AS chat_time_sec'),
    DB::raw('CASE WHEN type = "call" THEN time_in_secs END AS call_time_sec'),
    DB::raw('ROUND(SUM((spent_points/'.$valor_poinst_value->puntos_por_dolar.')),2) as total_sales'))
    ->whereIn('session_id', $ids_session)
    ->whereDate('created_at','>=',$from)
    ->whereDate('created_at','<=',$to)
    ->groupBy('session_id')
    ->get();

data result the my query code

{
    "session_id": "-N5fKtOYHJNvSy6Jj0Lj",
    "chat_time_sec": 5,
    "call_time_sec": null,
    "total_sales": "0.05"
},
{
    "session_id": "-N5fLhJ_kEa7RZWpASLu",
    "chat_time_sec": 7,
    "call_time_sec": null,
    "total_sales": "0.30"
}...

result that I hope to obtain

{
    "session_id": "-N5fKtOYHJNvSy6Jj0Lj",
    "chat_time_sec": 5,
    "call_time_sec": 15,
    "total_sales": "0.05"
},
{
    "session_id": "-N5fLhJ_kEa7RZWpASLu",
    "chat_time_sec": 7,
    "call_time_sec": 15,
    "total_sales": "0.30"
}

>Solution :

You need to add an aggregation function to your case, MAX shoudl do the trick

$sub = DB::table('session_details')
    ->select('session_id',
    DB::raw('MAX(CASE WHEN type = "chat" THEN time_in_secs END) AS chat_time_sec'),
    DB::raw('MAX(CASE WHEN type = "call" THEN time_in_secs END) AS call_time_sec'),
    DB::raw('ROUND(SUM((spent_points/'.$valor_poinst_value->puntos_por_dolar.')),2) as total_sales'))
    ->whereIn('session_id', $ids_session)
    ->whereDate('created_at','>=',$from)
    ->whereDate('created_at','<=',$to)
    ->groupBy('session_id')
    ->get();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading