原表结构如下,其中ID QK 两列都有重复,希望以ID分组,查询每组QK重复出现次数最多的结果,如果次数相同,随机取一条,并统计次数
ID QK
1 a
1 a
1 b
2 c
2 d
2 d
3 a
3 b
希望得到的结果是
ID QK CS
1 a 2
2 d 2
3 a 1
先子查询用分组 having max() 找出具体的id,然后根据id in(子查询结果)
select id,qk,count(qk) cs from 表名 group by qk order by cs desc limit 0,1;
select top(3)id,qk,COUNT(qk) as total
from #t
group by id,qk
order by total desc