关于DISTINCT的问题

北京菠菜 2003-12-12 07:43:07
表temp中有字段personid,relationid,name,sex

我想实现的功能是,从表中读出personid,relationid,name这三个字段中不完全相同的记录,同时还想加入sex字段,怎么办?

我以前这样写的Select Distinct personid,relationid,name from temp 但是这样不能加入sex了
...全文
46 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 元老 2003-12-13
  • 打赏
  • 举报
回复
--下面是数据测试

--测试数据
declare @t table(personid int,relationid int,name varchar(1),sex varchar(2))
insert into @t
select 1,1,1,'男'
union all select 1,1,1,'女'
union all select 1,2,3,'男'
union all select 1,3,4,'男'

--方法1.如果表中就这几个字段,可以用这种方法
select personid,relationid,name,sex=min(sex)
from @t group by personid,relationid,name

--方法2.适用一表中还有其他字段的情况
select * from @t a
where sex=(select top 1 sex from @t
where personid=a.personid and relationid=a.relationid and name=a.name)

/*--测试结果
方法1.
personid relationid name sex
----------- ----------- ---- ----
1 1 1 男
1 2 3 男
1 3 4 男

(所影响的行数为 3 行)

方法2.
personid relationid name sex
----------- ----------- ---- ----
1 1 1 男
1 2 3 男
1 3 4 男

(所影响的行数为 3 行)

--*/
zjcxc 元老 2003-12-13
  • 打赏
  • 举报
回复
--方法2.适用一表中还有其他字段的情况
select * from 表 a
where sex=(select top 1 sex from 表
where personid=a.personid and relationid=a.relationid and name=a.name)
zjcxc 元老 2003-12-13
  • 打赏
  • 举报
回复
select personid,relationid,name,sex=min(sex)
from 表 group by personid,relationid,name

dlpseeyou 2003-12-13
  • 打赏
  • 举报
回复
select personid,relationid,name,sex from temp group by personid,relationid,name
北京菠菜 2003-12-13
  • 打赏
  • 举报
回复
不对啊,还是出不来我想要的结果

我的表中的数据时这样的

personid relationid name sex
1 1 1 男
1 1 1 女
1 2 3 男
1 3 4 男


我想的结果是只获得三条记录,即将(1 1 1 女)这条去掉
CrazyFor 2003-12-12
  • 打赏
  • 举报
回复
select personid,relationid,name,sex from table group by personid,relationid,name,sex
binshan 2003-12-12
  • 打赏
  • 举报
回复
select a.* from temp as a inner join (Select Distinct personid,relationid,name from temp) as b on a.personid=b.personid and a.relationid=b.relationid and a.name=b.name
txlicenhe 2003-12-12
  • 打赏
  • 举报
回复
select * from temp a
where sex = ( select max(sex) from temp where personid = a.personid
and relationid = a.relationid and name = a.name )

tiny_yan 2003-12-12
  • 打赏
  • 举报
回复
select a.* from temp as a,(Select Distinct personid,relationid,name from temp) as b where a.personid=b.personid and a.relationid=b.relationid and a.name=b.name

34,838

社区成员

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

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