这个sql该如何写

jhsfg 2004-11-22 12:43:24
id content buid
1 内容1 180
1 内容2 180
1 内容3 170
1 内容4 180
1 内容5 169
1 内容6 169


我想取buid不同的最前面3条的全部数据:
1 内容1 180
1 内容3 170
1 内容5 169

我想用 select DISTINCT top 3 buid,content id from table 可是不行
...全文
107 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
fenlin 2004-11-22
  • 打赏
  • 举报
回复
select * from 表 where id in(select min(id) from 表 group by buid)
zjcxc 元老 2004-11-22
  • 打赏
  • 举报
回复
--或者是:
select top 3 a.*
from 表 a,(select id=min(id) from 表 group by buid)b
where a.id=b.id
zjcxc 元老 2004-11-22
  • 打赏
  • 举报
回复
--那直接这样就行了
select top 3 * from 表 a
not exists(select * from 表 where buid=a.buid and id<a.id)


jhsfg 2004-11-22
  • 打赏
  • 举报
回复
zjcxc(邹建) 不好意思。表应该是这样的
id content buid
1 内容1 180
2 内容2 180
3 内容3 170
4 内容4 180
5 内容5 169
6 内容6 169

id 就是主键
zjcxc 元老 2004-11-22
  • 打赏
  • 举报
回复
--如果不能改表结构,同用临时表增加辅助字段可以解决

select nid=identity(int),* into #t from 源表
select top 3 * from #t a
not exists(select * from #t where buid=a.buid and nid<a.nid)
drop table #t
yesyesyes 2004-11-22
  • 打赏
  • 举报
回复
select DISTINCT top 3 buid,content,id from table
zjcxc 元老 2004-11-22
  • 打赏
  • 举报
回复
1. distinct 是对整条记录判断重复,而不是对某个字段

2. 如果楼主的表结构就是列出的那样,没有主键,则不可能直接查询得出,楼上的方法会产生问题(把楼主的示例数据中的第一条记录的id设置为2,则楼上的方法就不正确了)

huwgao 2004-11-22
  • 打赏
  • 举报
回复
--生成测试数据
declare @t table(id int,content varchar(5),buid int)
insert into @t select 1,'内容1',180
union all select 1,'内容2',180
union all select 1,'内容3',170
union all select 1,'内容4',180
union all select 1,'内容5',169
union all select 1,'内容6',169

--如果id有可能不同
select top 3 a.id,a.content,a.buid
from @t a
join(select content=min(content),buid from @t group by buid) b
on a.content=b.content
order by a.buid desc

--如果id都是一样
select top 3 id=min(id),content=min(content),buid
from @t
group by buid
order by buid desc

--返回
(所影响的行数为 6 行)

id content buid
----------- ------- -----------
1 内容1 180
1 内容3 170
1 内容5 169

(所影响的行数为 3 行)

34,576

社区成员

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

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