普通网友 2016-06-11 20:40
浏览 140
已采纳

多个字段的Laravel SUM使用原始查询返回null

The following is my query :

 $sales = DB::table('sales')
        ->leftJoin('category_sales', 'category_sales.sale_id', '=', 'sales.id')
        ->leftJoin('department_sales', 'department_sales.sale_id', '=', 'sales.id')
        ->leftJoin('store_configs', 'store_configs.id', '=', 'sales.store_config_id')
        ->select('sales.date',
            DB::raw('store_configs.store_dba'),
            DB::raw('sales.id'),
            DB::raw('(sales.taxable + sales.non_taxable + category_sales.amount + department_sales.amount) as total_sales'),
            DB::raw('0.0825*(sales.taxable + category_sales.amount + department_sales.amount) as total_tax'))
        ->groupBy('date')->orderBy('date', 'desc')
        ->get();

I get the right value when I have values on category_sales and department_sales table. Lets say, I do not have any amount value for the sales_id in category_sales table, the final result for total_sales and total_tax is null.

My question is : how would I still sum the values of fields if the data is present ?

taxable, non_taxable, and amount'

in category_sales and department_sales are integer with defaults to 0

My table structure just for an idea and is similar with department_sales:

CREATE TABLE `category_sales` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`amount` int(11) NOT NULL DEFAULT '0',
`category_id` int(10) unsigned DEFAULT NULL,
`sale_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `category_sales_category_id_index` (`category_id`),
KEY `category_sales_sale_id_index` (`sale_id`),
CONSTRAINT `category_sales_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE,
CONSTRAINT `category_sales_sale_id_foreign` FOREIGN KEY (`sale_id`) REFERENCES `sales` (`id`) ON DELETE CASCADE) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  • 写回答

2条回答 默认 最新

  • dongzhu3548 2016-06-11 21:10
    关注

    You can wrap nullable fields into IFNULL() function, something like this:

    DB::raw('(IFNULL(sales.taxable,0)
     + IFNULL(sales.non_taxable,0)
     + IFNULL(category_sales.amount,0)
     + IFNULL(department_sales.amount,0)
    ) as total_sales'),
    DB::raw('0.0825*(IFNULL(sales.taxable,0) 
     + IFNULL(category_sales.amount,0)
     + IFNULL(department_sales.amount,0)) as total_tax'))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化