我有這樣計算並在相同的查詢欄選擇最大
+------+------------+------+
| user | date | code |
+------+------------+------+
| 1 | 2016-01-01 | AB |
| 2 | 2016-02-03 | AS |
| 3 | 2016-02-03 | AT |
| 1 | 2016-01-27 | AB |
| 2 | 2016-02-24 | AT |
| 1 | 2016-01-23 | AS |
| 2 | 2016-02-23 | AB |
| 1 | 2016-02-16 | AS |
| 1 | 2016-02-24 | AT |
+------+------------+------+
一個數據集,我需要的是這樣的
+------+---------------------------+
| user | max(count(distinct(code)) |
+------+---------------------------+
| 1 | 2 |
| 2 | 3 |
| 3 | 1 |
+------+---------------------------+
所以我用這個查詢
select t1.user, t1.month(date), count(distinct(`code`)) cod
from mytable t1
inner join
(select user, max(count(distinct(`code`))) max_count
from mytable
group by user) t2
on t1.user = t2.user
and t1.cod = t2.max_count`
但是我得到這個:
錯誤代碼1111的使用無效組功能
您不能像這樣一起使用多個聚合。我很困惑爲什麼用戶1返回2個代碼 - 爲什麼不是AB,AS和AT? – sgeddes
因爲這個想法每個月都會計算出不同的結果,並選擇該計數的最大值 –