如何取相同ID中首条记录?

zhengjialon 2009-07-15 12:14:22
有某表:
ID 子ID 客户名 客户订单号 金额
1 1 aaa 10001 1000
1 2 bbb 20002 2000
1 3 ccc 30004 1140
2 1 www 10100 3000
2 2 qqq 32000 4500

得到结果:
ID 子ID 客户名 客户订单号 金额
1 1 aaa 10001 1000
2 1 www 10100 3000
...全文
61 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhengjialon 2009-07-16
  • 打赏
  • 举报
回复
用了feixianxxx的,速度还不错,not exists 太慢了,谢各位!
feixianxxx 2009-07-15
  • 打赏
  • 举报
回复
select * from tb a
where 子ID = (
select top 1 子ID from tb
where id=a.id
order by 子ID
)
playwarcraft 2009-07-15
  • 打赏
  • 举报
回复

--SQL2005

select ID ,子ID ,客户名, 客户订单号, 金额
from
(select *, tmp=row_number() over (partition by ID order by getdate())
from T
) A
where tmp=1
jiangshun 2009-07-15
  • 打赏
  • 举报
回复

-----------------------------------------

--> 测试时间:2009-07-15
--> 我的淘宝:http://shop36766744.taobao.com/

--------------------------------------------------

if object_id('[tb]') is not null drop table [tb]
create table [tb]([ID] int,[子ID] int,[客户名] varchar(3),[客户订单号] int,[金额] int)
insert [tb]
select 1,1,'aaa',10001,1000 union all
select 1,2,'bbb',20002,2000 union all
select 1,3,'ccc',30004,1140 union all
select 2,1,'www',10100,3000 union all
select 2,2,'qqq',32000,4500

select * from [tb] t where not exists(select 1 from tb where T.id=id and T.子ID>子ID)
/*
ID 子ID 客户名 客户订单号 金额
----------- ----------- ---- ----------- -----------
1 1 aaa 10001 1000
2 1 www 10100 3000

(所影响的行数为 2 行)

*/

drop table TB
playwarcraft 2009-07-15
  • 打赏
  • 举报
回复
select * from T as A
where not exists(select 1 from T where ID=A.ID and 子ID<A.子ID)
昵称被占用了 2009-07-15
  • 打赏
  • 举报
回复
select * from tb a
where not exists (
select 1 from tb
where id=a.id
and 子ID <a.子ID
)
appleller 2009-07-15
  • 打赏
  • 举报
回复
select * from tb a where not exists (select 1 from tb where id=a.id
and 子ID <a.子ID )
whiteyundd 2009-07-15
  • 打赏
  • 举报
回复
select * from(
select *,ROW_NUMBER() over(PARTITION BY id order by 子ID) rn from tb
) t
where rn=1

34,593

社区成员

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

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