1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

  2. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

laravel left join for same table with different date range

Discussão em 'Outras Linguagens' iniciado por Stack, Abril 13, 2021.

  1. Stack

    Stack Membro Participativo

    Hello I am new on Laravel, the following SQL is verified working well as I expected, However, I can't make it work in Laravel......

    Might I have your help

    select *, SUM(CASE WHEN `parts_trans`.`in_out` = "In" THEN `parts_trans`.`qty` else -1 * `parts_trans`.`qty` END)as amount
    from `parts_trans`
    left join (
    SELECT `id`, SUM(CASE WHEN `in_out` = "Out" THEN qty END)as amount_out , SUM(CASE WHEN `in_out` = "In" THEN qty END)as amount_in
    FROM `parts_trans`
    WHERE `updated_at` between '2013-03-26' and '2021-04-26'
    group by `part_info_id`
    ) as p2
    on `parts_trans`.`id` = `p2`.`id`
    group by `parts_trans`.`part_info_id`


    I had try

    $from = date('Y-m-d', strtotime('-90 days'));
    $to = date('Y-m-d');

    $grid->model()
    ->selectRaw('*, SUM(CASE WHEN `in_out` = "Out" THEN `qty` END)as amount_out , SUM(CASE WHEN `in_out` = "In" THEN `qty` END) as amount_in')
    ->whereBetween('updated_at', [$from, $to])
    ->groupBy('part_info_id')
    ->leftJoin('parts_trans AS p2', function ($join) {
    $join->on('p2.id', '=', 'parts_trans.id')
    ->select('p2.id', 'SUM(CASE WHEN `p2.in_out` = "In" THEN `p2.qty` else -1 * `p2.qty` END)as amount')
    ->groupBy('p2.part_info_id');
    });


    it turn out

    SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'in_out' in field list is ambiguous
    (SQL: select count(*) as aggregate from (
    select *, SUM(CASE WHEN `in_out` = "Out" THEN `qty` END)as amount_out , SUM(CASE WHEN `in_out` = "In" THEN `qty` END) as amount_in
    from `parts_trans`
    left join `parts_trans` as `p2`
    on `p2`.`id` = `parts_trans`.`id`
    where `updated_at` between 2021-01-13 and 2021-04-13 group by `part_info_id`) as `aggregate_table`)

    Continue reading...

Compartilhe esta Página