2016-03-15 25 views
0

我有這樣計算並在相同的查詢欄選擇最大

+------+------------+------+ 
| 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

您不能像這樣一起使用多個聚合。我很困惑爲什麼用戶1返回2個代碼 - 爲什麼不是AB,AS和AT? – sgeddes

+0

因爲這個想法每個月都會計算出不同的結果,並選擇該計數的最大值 –

回答

0

嘗試此,使用內組由usermonth和外組由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 
+0

感謝@Dylan Su。我只是有一個問題,爲什麼我的查詢不起作用?,這是爲了「在第一部分計數(distinct('code'))cod」還是爲什麼? –

+0

不允許同時使用兩個聚合函數:max(count()) –

0

的嘗試以下方法:

select `user`, max(`max_count`) 
from (
    select `user`, count(`code`) as `max_count` 
    from `mytable` 
    group by `user`, `code`) t 
group by `user`