关于查找的问题

kinvb 2003-12-27 11:19:33
表A 中有如下记录:
模号 货品编号
001 A001
001 A002
001 A003
002 A001
002 D001
002 F001
... ...
要得出结果如下:
001 A001 (A001 可以任意一个如(A002或A003))
002 F001 (F001 可以任意一个如(A001或D001))
... ...
以模号为组,在每组中必须取出一条记录.
...全文
35 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
1ssp 2003-12-27
  • 打赏
  • 举报
回复
你想查找什么条件的记录,你说清楚了,在回答.....
dlpseeyou 2003-12-27
  • 打赏
  • 举报
回复
select 模号,max(货品编号) as 货品编号
from A
group by 模号
zjcxc 元老 2003-12-27
  • 打赏
  • 举报
回复
--下面是测试

--测试数据
declare @表 table(模号 varchar(10),货品编号 varchar(10))
insert @表
select '001','A001'
union all select '001','A002'
union all select '001','A003'
union all select '002','A001'
union all select '002','D001'
union all select '002','F001'

--下面是几种查询方法:

--取最小一个
select 模号,货品编号=max(货品编号)
from @表 group by 模号

--取最大一个
select 模号,货品编号=min(货品编号)
from @表 group by 模号

--取第一个
select 模号
,货品编号=(select top 1 货品编号 from @表 where 模号=a.模号)
from(select distinct 模号 from @表) a

--随机取一个
select 模号
,货品编号=(select top 1 货品编号 from @表 where 模号=a.模号 order by newid())
from(select distinct 模号 from @表) a

/*--测试结果

--取最小一个

模号 货品编号
---------- ----------
001 A003
002 F001

(所影响的行数为 2 行)


--取最大一个

模号 货品编号
---------- ----------
001 A001
002 A001

(所影响的行数为 2 行)


--取第一个

模号 货品编号
---------- ----------
001 A001
002 A001

(所影响的行数为 2 行)


--随机取一个

模号 货品编号
---------- ----------
001 A002
002 F001

(所影响的行数为 2 行)
--*/
zjcxc 元老 2003-12-27
  • 打赏
  • 举报
回复
--上面犯了一个错误,改一下:


--取最小一个
select 模号,货品编号=max(货品编号)
from 表 group by 模号

--取最大一个
select 模号,货品编号=min(货品编号)
from 表 group by 模号

--取第一个
select 模号
,货品编号=(select top 1 货品编号 from 表 where 模号=a.模号)
from(select distinct 模号 from 表) a

--随机取一个
select 模号
,货品编号=(select top 1 货品编号 from 表 where 模号=a.模号 order by newid())
from(select distinct 模号 from 表) a
zjcxc 元老 2003-12-27
  • 打赏
  • 举报
回复
select 模号,货品编号=max(货品编号) from 表

--或:
select 模号,货品编号=min(货品编号) from 表

--或:随机取一个:
select 模号,货品编号=(select top 1 货品编号 from 表 where 模号=a.模号 order by newid()) from(select distinct 模号 from 表) a
wzh1215 2003-12-27
  • 打赏
  • 举报
回复
create table #a(id varchar(10),id2 varchar(10))
insert #a values('001','A001')
insert #a values('001','A002')
insert #a values('001','A003')
insert #a values('002','A001')
insert #a values('002','D001')
insert #a values('002','F001')
select * from #a
select id,(select top 1 id2 from #a aa where aa.id=id order by newid()) as id2
from #a group by id
wzh1215 2003-12-27
  • 打赏
  • 举报
回复
select 模号,max((select top 1 货品编号 from A aa where aa.模号=模号 order by newid()))
from A group by 模号
victorycyz 2003-12-27
  • 打赏
  • 举报
回复
select 模号,min(货品编号) as 货品编号
from A
group by 模号

34,838

社区成员

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

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