我有这样的数据集
+------+------------+------+
| 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.无效使用组功能
答案 0 :(得分:0)
尝试以下方法:
select `user`, max(`max_count`)
from (
select `user`, count(`code`) as `max_count`
from `mytable`
group by `user`, `code` ) t
group by `user`
答案 1 :(得分:0)
尝试使用内部组user
,month
和外部组user
。
select t.user, max(t.cod) as max_cnt
from (
select user, month(date) as month, count(distinct(`code`)) cod
from mytable
group by user, month
) t
group by t.user