SQL查询 - 两列,重复数据 - 需要最频繁

时间:2015-04-26 01:22:41

标签: sql

我可以对我尝试在Access中创建的查询使用一些指导。以下是我的数据:

UserName    ComputerName

John    Computer 1
John    Computer 1
John    Computer 1
John    Computer 1
John    Computer 2
John    Computer 2
Sally   Computer 1
Sally   Computer 1
Sally   Computer 2
Mike    Computer 1
Megan   Computer 2

我想检索每个用户访问最多的ComputerName。这是我想看到的。

John         Computer 1
Sally        Computer 1
Mike         Computer 1
Megan        Computer 2

正如您所看到的,UserName字段中有重复的条目(John,Sally),但该字段中可能只有一个名称实例(Mike,Megan)。

感谢任何帮助。提前谢谢。

亲切的问候, 达林

1 个答案:

答案 0 :(得分:0)

下面的查询使用自联接来获取每个用户最常用的计算机名称。

select t1.UserName, t1.ComputerName from (
    select UserName, ComputerName, count(*) as cnt
    from mytable
    group by UserName, ComputerName
) as t1 left join (
    select UserName, ComputerName, count(*) as cnt
    from mytable
    group by UserName, ComputerName
) as t2 on t1.UserName = t2.UserName and t2.cnt > t1.cnt
group by t1.UserName, t1.ComputerName
having count(t2.cnt) = 0