请教Sql语句的快捷写法

MicroSoftor 2011-11-11 02:24:14
征求一个Sql语句的写法,要求效率高、快捷。
数据表(tbx)是这样的
id parentid type name
1 1 正常 a
2 1 不正常 b
3 1 不正常 c
4 2 正常 d
5 2 不正常 e
6 2 不正常 f

想从中取出以下数据,
type="不正常"且每个parentId只取一个(按id以asc方式排序),即获取后的数据为
id parentid type name
2 1 不正常 b
5 2 不正常 e

请各位支招,要效率高效,谢谢各位了
...全文
120 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
MicroSoftor 2011-11-11
  • 打赏
  • 举报
回复
非常感谢各位网友的热心支持,我计划重新调整下设计方式,结贴给分。Over
MicroSoftor 2011-11-11
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 jxjdzwang5555 的回复:]

sele id, distinct parentid, type, name from tbx where type='不正常' order by id
???
[/Quote]
这种方式是不行的。
jxjdzwang5555 2011-11-11
  • 打赏
  • 举报
回复
sele id, distinct parentid, type, name from tbx where type='不正常' order by id
???
MicroSoftor 2011-11-11
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 roy_88 的回复:]

SQL code
select * from tbx as a where type='不正常'
and not exists(select 1 from tbx where parentId=a.parentId and type=a.type and ID<a.ID)
[/Quote]

方法很好,多谢了
MicroSoftor 2011-11-11
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ssp2009 的回复:]

SQL code
select * from tbx a
where id=(select min(tbx) from tbx where parentid=a.parentid and type='不正常')
order by id
[/Quote]

感谢,除了使用min函数外还有其他的方式么?
Mr_Nice 2011-11-11
  • 打赏
  • 举报
回复
if object_id('[tb]') is not null drop table [tb]
go
create table [tb] (id int,parentid int,type nvarchar(6),name nvarchar(2))
insert into [tb]
select 1,1,'正常','a' union all
select 2,1,'不正常','b' union all
select 3,1,'不正常','c' union all
select 4,2,'正常','d' union all
select 5,2,'不正常','e' union all
select 6,2,'不正常','f'

select * from [tb]


select * from TB T where exists(select 1 from tb where parentid = T.parentid and id >t.id ) and type ='不正常'

/*
id parentid type name
2 1 不正常 b
5 2 不正常 e*/
中国风 2011-11-11
  • 打赏
  • 举报
回复
select * from tbx as a 
where type='不正常' and
ID=(select MIN(ID) from tbx where parentId=a.parentId and type=a.type
)
中国风 2011-11-11
  • 打赏
  • 举报
回复
select * from tbx as a where type='不正常'
and not exists(select 1 from tbx where parentId=a.parentId and type=a.type and ID<a.ID)
快溜 2011-11-11
  • 打赏
  • 举报
回复
select * from tbx a
where id=(select min(tbx) from tbx where parentid=a.parentid and type='不正常')
order by id

34,838

社区成员

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

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