普通网友 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条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大