求:一个分组,选取前N条纪录的SQL写法

513cat 2003-07-31 06:32:25
现有数据表TableA,
Col1 Col2 Col3 Col4
----------------

其中Col4为Integer
现在需要以Col1分组,选择出每组的以Col4为和的前十条纪录

比如Col2记录的是公司名称,Col1纪录的是该公司所在城市名称,Col4记录的是该公司的员工总数。那么现在需要选择全国每个城市中,员工最多的前N家公司,
即:北京的公司员工最多的前N家公司,上海的公司员工最多的前N前公司。。。。。。等等。
...全文
42 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
qianguob 2003-07-31
  • 打赏
  • 举报
回复
select top 10 col2,col4 from table
group by col2,col4
order by col4 desc

我想这样应该可以实现你的要求。
nboys 2003-07-31
  • 打赏
  • 举报
回复
select top 10 * from TableA d where Col4=(select max(Col4) from TableA where Col1=d.Col1)
nboys 2003-07-31
  • 打赏
  • 举报
回复
select * from TableA d where Col4=(select max(Col4) from TableA where Col2=d.Col2 and Col3=d.Col3)
zjcxc 2003-07-31
  • 打赏
  • 举报
回复
照我的理解话,应该如下处理:

--定义数据测试环境,用表名代表城市名,字段名代表公司名,字段id代表员工数
declare @tb table(Cite varchar(50),CoName varchar(50),col3 int,col4 int)
insert into @tb(cite,coname,col4)
select object_name(id),name,colid from syscolumns


--为了处理方便,使用临时表
select id=identity(int,1,1),cite,coname,sum(col4) as col4
into #tb
from @tb group by cite,coname


--查询得到结果
select * from #tb a
where id in (select top 10 id from #tb
where cite=a.cite and coname=a.coname
order by col4 desc)

--删除临时表
drop table #tb
zjcxc 2003-07-31
  • 打赏
  • 举报
回复
你的分组条件不对
如果照你的意思统计的话,每个城市都只会有一条总记录,当然不存在你说的前10个的问题.


照你后面的意思
比如Col2记录的是公司名称,Col1纪录的是该公司所在城市名称,Col4记录的是该公司的员工总数。那么现在需要选择全国每个城市中,员工最多的前N家公司,
即:北京的公司员工最多的前N家公司,上海的公司员工最多的前N前公司。。。。。。等等。


应该是按col1,col2分组才对.
不知我的理解是否正确?
lggege8000 2003-07-31
  • 打赏
  • 举报
回复
select * from 表 tem where col4 in (select top 10 col4 from 表 a tem where coll=a.coll order by a.coll desc)
woyaofengle 2003-07-31
  • 打赏
  • 举报
回复
select * from 表 tem where Col4 in (select top 10 Col4 from 表 where Col1=tem.Col1)
txlicenhe 2003-07-31
  • 打赏
  • 举报
回复
select * from TableA a where Col4 in (select top 10 Col4 from TableA where Col1=a.Col1 order by Col4 desc)
edisonwong 2003-07-31
  • 打赏
  • 举报
回复
select col1,col2,col4
from tab
where (select count(*)
from tab b
where b.col1=tab.col1
and b.col4>=tab.col4)<=10
order by 1,3 desc
pengdali 2003-07-31
  • 打赏
  • 举报
回复
select * from 表 tem where Col4 in (select top 10 Col4 from 表 where Col1=tem.Col1 order by Col4 desc)
pengdali 2003-07-31
  • 打赏
  • 举报
回复
select * from 表 tem where Col4 in (select top 10 Col4 from 表 where Col1=tem.Col1)

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧