0

I got the following code that gonna return the sum of score if tgl is '2023-01-01' and then that return value will be selected again to not show any null that the query find

SELECT *
FROM (
    SELECT `kodeSales`,
        `departemenId`,
        `tgl`, 
        (SELECT SUM(CASE WHEN tgl IN ('2023-01-01') THEN score END)) AS '1'
    FROM `history_penjualan` 
    WHERE `tgl` BETWEEN '2023-01-01' AND '2023-01-30' 
        `departemenId` = '28' 
    GROUP BY `tgl`
) AS temp
WHERE '1' IS NOT NULL

How do I do this in laravel eloquent or query builder ?

1
  • I have add an answer check it. If you want to convert more queries try this website. sql2builder.github.io Commented Feb 10, 2023 at 5:31

1 Answer 1

1

Try this way,

I tried this and it works. but in here you can change the ->having() statement as havingRaw("'1' IS NOT NULL") or I provided code also works.

$sum_of_score = DB::table('history_penjualan')
        ->select('kodeSales', 'departemenId', 'tgl', DB::raw("SUM(CASE WHEN tgl = '2023-01-01' THEN score END) AS '1'"))
        ->whereBetween('tgl', ['2023-01-01', '2023-01-30'])
        ->where('departemenId', '=', 28)
        ->groupBy('tgl')
        ->having('1', '!=', null)
        ->get();

or if you need query in dynamic try this way,

$query = DB::table('history_penjualan')
        ->select(DB::raw('kodeSales, departemenId, tgl, SUM(CASE WHEN tgl = "2023-01-01" THEN score END) as "1"'))
        ->whereBetween('tgl', ['2023-01-01', '2023-01-30'])
        ->where('departemenId', '=', '28')
        ->groupBy('tgl');

$final_data = $query->having('1', '<>', null)->get();

If this is not your expected answer please leave a comment, I'll give another way to do this :)

Sign up to request clarification or add additional context in comments.

2 Comments

I kinda need what i ask because the query will be dynamic i will add a ton of SUM and Having and/or Where Clause
OK, I have edited my answer check it bro.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.