TSQL模式(例如平均数、中位数、众数)

13

我正在尝试计算表格中一系列idsofInterest的众数,每个idsofInterest都有相应的valueOfInterest:

idsOfInterest | valueOfInterest  
2             | 1A  
2             | 1A  
2             | 3B  
1             | 2A  
1             | 2C  
1             | 2A  
4             | 3B  
4             | 3B  
4             | 4C  

但是有数百万行。
每个idOfInterest列表都足够长,不会出现多模问题。理想情况下,我希望得到类似于

idsOfInterest | modeValueOfInterest  
1             | 2A  
2             | 1A  
3             | 3C  
4             | 3B

可能是SQL Server模式SQL的重复问题。 - Karl Kieninger
这绝对是一个重复的问题,但我必须说,我更喜欢@Gordon Linoff的答案,胜过其他问题上的任何回答。 - DeanOC
1个回答

18

众数是最常见的值。您可以使用聚合和row_number()来获取它:

select idsOfInterest, valueOfInterest
from (select idsOfInterest, valueOfInterest, count(*) as cnt,
             row_number() over (partition by idsOfInterest order by count(*) desc) as seqnum
      from table t
      group by idsOfInterest, valueOfInterest
     ) t
where seqnum = 1;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接