laravel如何写这种的sql语句?

情况是这样,我建立一张水果每日销量表

CREATE TABLE `shuiguo` (
  `id` int(11) NOT NULL,
  `type` varchar(255) DEFAULT NULL COMMENT '类型,包括苹果,香蕉,梨,葡萄,西瓜',
  `value` varchar(10) DEFAULT NULL COMMENT '销量',
  `day` varchar(10) DEFAULT NULL COMMENT '日期'
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4

我想着想知道某个日期的苹果,梨,葡萄 销量
最简单sql语句有

select `value` from shuiguo where `type`='苹果' and day='日期';
select `value` from shuiguo where `type`='梨'  and day='日期';
select `value` from shuiguo where `type`='葡萄'  and day='日期';

我就需要执行三次sql语句,有没有一条语句就能搞定的?
然后如何我想要一段日期内的那三种水果的销量,sql语句要怎么写的?

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 8
ShuiguoModel::selectRaw('sum(value) as value')->groupBy('type','day')->get();
3个月前 评论
// 指定日期 $date = ' 日期 ';

// 查询苹果、梨和葡萄的值
 $appleQuery = DB::table ('shuiguo') ->select ('value', DB::raw ("' 苹果 ' as type")) ->where ('type', ' 苹果 ') ->where ('day', $date);

$pearQuery = DB::table ('shuiguo') ->select ('value', DB::raw ("' 梨 ' as type")) ->where ('type', ' 梨 ') ->where ('day', $date);

$grapeQuery = DB::table ('shuiguo') ->select ('value', DB::raw ("' 葡萄 ' as type")) ->where ('type', ' 葡萄 ') ->where ('day', $date);

// 合并查询
 $results = $appleQuery ->unionAll ($pearQuery) ->unionAll ($grapeQuery) ->get (); 
3个月前 评论
keyboby 3个月前
//某个日期
ShuiGuo::query()
    ->whereIn('type', ['苹果','梨','葡萄'])
    ->where('day','=', '日期')
    ->groupBy('type','value')
    ->get(['type','value']);
//select `type`, `value` from `shui_guo` where `type` in ('苹果', '梨', '葡萄') and `day` = '日期' group by `type`, `value` 

//某个时间段
ShuiGuo::query()
    ->whereIn('type', ['苹果','梨','葡萄'])
    ->whereBetween('day',['日期开始','日期结束'])
    ->groupBy('type')
    ->selectRaw("type,sum(value) as sum_value")
    ->get();
//select type,sum(value) as sum_value from `shui_guo` where `type` in ('苹果', '梨', '葡萄') and `day` between '日期开始' and '日期结束' group by `type` 
3个月前 评论
donggan (楼主) 3个月前
ShuiguoModel::selectRaw('type,day,sum(value) as value')
->whereBetween('day', [start_day,end_day])
->whereIn('type', ["苹果","葡萄","梨"])
->groupBy('type','day')->get();
3个月前 评论
Mutoulee

想知道某个日期的苹果,梨,葡萄 销量 :

$data = DB::table ('shuiguo')
    ->whereIn('type', ['苹果', '梨', '葡萄'])
    ->where('day', $day)
    ->get();

想要一段日期内的那三种水果的销量:

$data = DB::table ('shuiguo')
    ->whereIn('type', ['苹果', '梨', '葡萄'])
    ->whereBetween('day', [$day1, $day2])
    ->get()
    ->groupBy('type')
foreach($data as $group){
    // 该时间段内每一种水果的销量
    echo $group->pluck('value')->sum();
}

没测试过,仅供参考。

3个月前 评论

select * from t where (name,type) in (('张三','A'),('李四','B'),('王五','C'))

3个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!