求sql写法,取得表格中,数据分组后,每组前3名的记录,不知该如何写?

gos_q 2008-06-20 02:59:18
表格如下
ID Group Sales Amount
1 A Sales1 100
2 A Sales2 120
3 A Sales3 105
4 A Sales4 103
5 B Sales1 203
6 B Sales2 250
7 B Sales5 300
8 B Sales6 301
. . .
. . .
. . .

希望得到结果如下

Group Sales Amount
A Sales2 120
A Sales3 105
A Sales4 103
B Sales6 301
B Sales5 300
B Sales2 250

请问sql应该如何写?

...全文
110 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
gos_q 2008-06-20
  • 打赏
  • 举报
回复
谢谢大家,现在结贴。
ydage 2008-06-20
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 ydage 的回复:]
--假设上述表名为tb:
SELECT Group,Salces,Amount
FROM tb t
WHERE id IN(SELECT TOP 3 id FROM tb WHERE group = t.group ORDER BY Amount)
[/Quote]

忘记加降序排列了:
SELECT Group,Salces,Amount
FROM tb t
WHERE id IN(SELECT TOP 3 id FROM tb WHERE group = t.group ORDER BY Amount DESC)
wgzaaa 2008-06-20
  • 打赏
  • 举报
回复
小小修正
select [Group],Sales,Amount from #t a
where id in(select top 3 id from #t b where a.[Group]=b.[Group] order by Amount desc)
order by [Group],Amount desc
pt1314917 2008-06-20
  • 打赏
  • 举报
回复

select * from 表名 a where id in (select top 3 id from 表名 where Group=a.Group order by amount desc)
nzperfect 2008-06-20
  • 打赏
  • 举报
回复
create table #T (ID int,[Group] varchar(2),Sales varchar(8),Amount int)
insert into #T
select 1,'A','Sales1',100 union all
select 2,'A','Sales2',120 union all
select 3,'A','Sales3',105 union all
select 4,'A','Sales4',103 union all
select 5,'B','Sales1',203 union all
select 6,'B','Sales2',250 union all
select 7,'B','Sales5',300 union all
select 8,'B','Sales6',301

select * from #T a where id in (select top 3 id from #T where [Group]=a.[Group] order by Amount desc)

/*
--------------------------
2 A Sales2 120
3 A Sales3 105
4 A Sales4 103
6 B Sales2 250
7 B Sales5 300
8 B Sales6 301
*/
utpcb 2008-06-20
  • 打赏
  • 举报
回复
select * from table a where id in (select top 3 id from table where id=a.id order by amount desc)
ydage 2008-06-20
  • 打赏
  • 举报
回复
--假设上述表名为tb:
SELECT Group,Salces,Amount
FROM tb t
WHERE id IN(SELECT TOP 3 id FROM tb WHERE group = t.group ORDER BY Amount)
Garnett_KG 2008-06-20
  • 打赏
  • 举报
回复
select * from table a where id in (select top 3 id from table where id=a.id order by amount desc)

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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