gpt4 book ai didi

php - Laravel Eloquent : multiple select and where clause query

转载 作者:行者123 更新时间:2023-11-29 20:06:55 35 4
gpt4 key购买 nike

我正在尝试从我的销售表中获取一个查询:

For each `Brand`    
`Brand` {
this month `sum(quantity)`
this month last year `sum(quantity)`
this year `sum(quantity)`
this last year `sum(quantity)`
`Brand` name
}
Next `Brand` {
this month `sum(quantity)`
this month last year `sum(quantity)`
this year `sum(quantity)`
this last year `sum(quantity)`
`Brand` name
}

我有这个,但它没有吐出任何东西。如果我删除 wheres,它将得到的总和不在我需要的日期范围内,所以我知道这是这个问题。我不确定我是否可以做多个地方

public function sales()
{

return $this->hasMany('App\Sale', 'account_vip_id', 'vip_id')
->select('brand', DB::raw('sum(quantity) as month'))->whereMonth('date','=',date('m'))
->addSelect('brand', DB::raw('sum(quantity) as month_last'))->whereDate('date','=',date('m Y',strtotime("-1 year")))
->addSelect('brand', DB::raw('sum(quantity) as year'))->whereYear('date','=',date('Y'))
->addSelect('brand', DB::raw('sum(quantity) as year_last'))->whereYear('date','=', date("Y",strtotime("-1 year")))
->groupBy('brand');

}

最佳答案

不幸的是,SQL 不能这样工作。您需要将 where 子句放在 sum 函数内。我创建了一个快速查询,以便让您更好地了解我在说什么...

SELECT 
brands.name,
SUM( IF( DATE_FORMAT(NOW(), '%y-%m') = DATE_FORMAT(sales.created_at, '%y-%m'), sales.quantity, 0) ) AS `month`,
SUM( IF( DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), '%y-%m') = DATE_FORMAT(sales.created_at, '%y-%m'), sales.quantity, 0) ) AS `last_month`,
SUM( IF( YEAR(CURDATE()) = YEAR(sales.created_at), sales.quantity, 0) ) AS `year`,
SUM( IF( YEAR(CURDATE()) - 1 = YEAR(sales.created_at), sales.quantity, 0) ) AS `last_year`
FROM brands
INNER JOIN sales ON brands.id = sales.brand_id
GROUP BY brands.name;

关于php - Laravel Eloquent : multiple select and where clause query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40310807/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com