SQL Server中一个SQL语句问题
时间:2011-11-29
来源:互联网
数据表MatchNumLog有字段:ID(自动编号),RuleID,MatchNum,Frequency(MatchNum的出现次数)
主键为RuleID和MatchNum,数据如下所示:
ID(自动编号) RuleID MatchNum Frequency
1 001 1 3
2 001 2 5
3 002 3 1
4 002 4 10
5 002 1 6
若要求各个RuleID出现次数最多(Frequency最大)的MatchNum,SQL语句该如何写?谢谢!
如上例要求的结果为:
2 001 2 5
4 002 4 10
主键为RuleID和MatchNum,数据如下所示:
ID(自动编号) RuleID MatchNum Frequency
1 001 1 3
2 001 2 5
3 002 3 1
4 002 4 10
5 002 1 6
若要求各个RuleID出现次数最多(Frequency最大)的MatchNum,SQL语句该如何写?谢谢!
如上例要求的结果为:
2 001 2 5
4 002 4 10
作者: niesen111 发布时间: 2011-11-29
SQL code
use Tempdb go --> --> if not object_id(N'Tempdb..#T') is null drop table #T Go Create table #T([ID] int,[RuleID] nvarchar(3),[MatchNum] int,[Frequency] int) Insert #T select 1,N'001',1,3 union all select 2,N'001',2,5 union all select 3,N'002',3,1 union all select 4,N'002',4,10 union all select 5,N'002',1,6 Go SELECT * FROM (Select *,COUNT(*)OVER(PARTITION BY [RuleID]) con,ROW_NUMBER()OVER(PARTITION BY [RuleID] ORDER BY [Frequency] desc) AS row from #T AS a )t WHERE row=1 /* ID RuleID MatchNum Frequency con row 2 001 2 5 2 1 4 002 4 10 3 1 */
作者: roy_88 发布时间: 2011-11-29
SQL code
select * from tb a where id=(select top 1 id from tb where RuleID=a.RuleID order by MatchNum desc,Frequency desc)
作者: ssp2009 发布时间: 2011-11-29
select t.* from MatchNumLog t where Frequency = (select max(Frequency) where RuleID = t.RuleID)
select t.* from MatchNumLog t where not exists (select 1 where RuleID = t.RuleID and Frequency > t.Frequency)
select t.* from MatchNumLog t where not exists (select 1 where RuleID = t.RuleID and Frequency > t.Frequency)
作者: dawugui 发布时间: 2011-11-29
select t.* from MatchNumLog t where Frequency = (select max(Frequency) from MatchNumLog where RuleID = t.RuleID)
select t.* from MatchNumLog t where not exists (select 1 from MatchNumLog where RuleID = t.RuleID and Frequency > t.Frequency)
select t.* from MatchNumLog t where not exists (select 1 from MatchNumLog where RuleID = t.RuleID and Frequency > t.Frequency)
作者: dawugui 发布时间: 2011-11-29
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28