我有一个表,看起来像这样:获取最常见/频繁的价值每个月
id | age | date
----|-----|--------------------
1 | 18 | 2016-07-1 00:00:00
2 | 20 | 2016-07-1 00:00:00
3 | 20 | 2016-07-1 00:00:00
4 | 22 | 2016-08-1 00:00:00
5 | 22 | 2016-08-1 00:00:00
6 | 30 | 2016-08-1 00:00:00
7 | 25 | 2016-09-1 00:00:00
,我需要得到每月+一年中最常见的年龄。
我有这个疑问至今:
$ages = User::selectRaw('age, MONTH(date) as month, YEAR(date) as year, count(*) as count')
->groupBy(['age', 'month', 'year'])
->orderBy('year', 'asc')
->orderBy('month', 'asc')
->get();
这只能得到数各年龄每个月+一年。我需要的东西,看起来像这样:
[
{
"age": 20,
"month": 7,
"year": 2016,
},
{
"age": 22,
"month": 8,
"year": 2016,
},
{
"age": 25,
"month": 9,
"year": 2016,
}
]
即七月(月== 7)二零一六年,有两个20岁和一名年满18,所以20是最常见的年龄。对于2016年8月,最常见的是22,依此类推......
对此有什么好的查询?谢谢。
是否确定substring_index必须返回正确的结果?我问,因为它似乎有点反直觉,它是在GROUP BY之后工作的。 – Strawberry
@Strawberry。 。 。 “GROUP BY”后的含义是什么?第一个查询中有两个聚合。 –
我想我在问你的'黑客'解决方案比我的'黑客'解决方案还少'黑客'。 – Strawberry