RAU*_*MAR 6 php mysql group-by laravel laravel-5
我需要将数据分组created_date,然后再次在affiliate_ad. 我正在使用这个
return DB::table($this->table)
->whereRaw($where['rawQuery'], isset($where['bindParams']) ? $where['bindParams'] : array())
->select('id', 'created_date','affiliate_ad', DB::raw('count(*) as total,count(affiliate_ad=1) as affiliate_ad_count,SUBSTRING(`created_date`, 1, 10) AS c_date'))
->groupBy('affiliate_ad','c_date')
->orderBy('c_date', 'desc')
->get();
Run Code Online (Sandbox Code Playgroud)
它给了我这样的结果
Collection {#385
#items: array:18 [
0 => {#386
+"id": 354766
+"created_date": "2018-01-10 10:16:27"
+"affiliate_ad": 1
+"total": 2
+"affiliate_ad_count": 1
+"c_date": "2018-01-10"
}
1 => {#384
+"id": 354730
+"created_date": "2018-01-10 10:10:39"
+"affiliate_ad": 0
+"total": 3
+"affiliate_ad_count": 4
+"c_date": "2018-01-10"
}
2 => {#387
+"id": 338263
+"created_date": "2018-01-08 10:10:52"
+"affiliate_ad": 0
+"total": 83
+"affiliate_ad_count": 83
+"c_date": "2018-01-08"
}
]
}
Run Code Online (Sandbox Code Playgroud)
在这里,如果您检查,在前两个索引中创建的日期是相同的。所以我想将它们分组在索引处的一个数组索引中0th作为multidimensional array分组affiliate_ad。实际查询构建为
SELECT id
, created_date
, affiliate_ad
, COUNT(*) total
, COUNT(affiliate_ad = 1) affiliate_ad_count
, SUBSTRING(created_date,1,10) c_date
FROM facebook_ad
WHERE facebook_id = 12345
AND reward_status = 0
AND (first_seen BETWEEN 0 AND 99999999)
GROUP
BY affiliate_ad
, c_date
ORDER
BY c_date desc
Run Code Online (Sandbox Code Playgroud)
我需要这样的输出
Collection {#385
#items: array:18 [
0 => [
0 => {#386
+"id": 354766
+"created_date": "2018-01-10 10:16:27"
+"affiliate_ad": 1
+"total": 2
+"affiliate_ad_count": 1
+"c_date": "2018-01-10"
}
1 => {#384
+"id": 354730
+"created_date": "2018-01-10 10:10:39"
+"affiliate_ad": 0
+"total": 3
+"affiliate_ad_count": 4
+"c_date": "2018-01-10"
}
]
1 => [
0 => {#387
+"id": 338263
+"created_date": "2018-01-08 10:10:52"
+"affiliate_ad": 0
+"total": 83
+"affiliate_ad_count": 83
+"c_date": "2018-01-08"
}
]
]
}
Run Code Online (Sandbox Code Playgroud)
获得类似于下图的效果
从查询中获得结果后,您可以考虑对其进行格式化。它已经返回给你一个集合。您可以添加->groupBy('c_date')->values()到集合中以检索给定的结果。如果删除->values()部分,它将保留分组日期作为键。