Mic*_*zer 12 sql t-sql sql-server-2008
我正在尝试计算一个表中的一系列idsofInterest的模式,每个都带有一个伴随的valueOfInterest:
idsOfInterest | valueOfInterest
2 | 1A
2 | 1A
2 | 3B
1 | 2A
1 | 2C
1 | 2A
4 | 3B
4 | 3B
4 | 4C
Run Code Online (Sandbox Code Playgroud)
但有数百万行.
每个idOfInterest列表都足够长,多模式不是问题.理想情况下,我想要像
idsOfInterest | modeValueOfInterest
1 | 2A
2 | 1A
3 | 3C
4 | 3B
Run Code Online (Sandbox Code Playgroud)
任何帮助赞赏.(使用MS SQL Server 2008)
Gor*_*off 16
该模式是最常见的值.你可以通过聚合得到这个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;
Run Code Online (Sandbox Code Playgroud)