高手看过来,高分请教SQL语句

bladewing 2005-02-18 04:37:53
test表的内容:
ID a b
1 1 2
2 1 3
3 2 3
4 2 3
5 3 1
6 4 1
要求:列出字段a的重复项,即得到结果为:
ID a b
1 1 2
2 1 3
3 2 3
4 2 3
...全文
209 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
bladewing 2005-02-21
  • 打赏
  • 举报
回复
感谢各位,马上结帖!
txlicenhe 2005-02-19
  • 打赏
  • 举报
回复
如果在得到上面结果的我要求只得a例有重复项的且b例项是最小的。
也是只得到
ID a b
1 1 2
3 2 3
而下面这些不要显示

2 1 3
4 2 3
-------------------------------------
是ID最小的吧?


select t.* from test t
where exists (select 1 from test where a = t.a and ID > t.id)
and not exists(select 1 from test where a = t.a and ID < t.id)


jiang130 2005-02-19
  • 打赏
  • 举报
回复
呵呵!having和where的區別是having可帶含聚合函數的條件!
Softlee81307 2005-02-19
  • 打赏
  • 举报
回复
Create Table Test(Id int,a int,b int)
insert into test
select 1,1,2 union all
select 2,1,3 union all
select 3,2,3 union all
select 4,2,3 union all
select 5,3,1 union all
select 6,4,1

-----------下面語句----------------
select min(id),a,min(b) from test group by a having count(*)>1
-------------結果------------------
ID a b
1 1 2
3 2 3

drop table test ----------刪除測試
zhaovbo 2005-02-19
  • 打赏
  • 举报
回复
select t.* from test t
where exists (select 1 from test where a = t.a and ID > t.id)
wjmsino 2005-02-18
  • 打赏
  • 举报
回复
我想借此问下:

如果在得到上面结果的我要求只得a例有重复项的且b例项是最小的。
也是只得到
ID a b
1 1 2
3 2 3
而下面这些不要显示

2 1 3
4 2 3


lishengyu 2005-02-18
  • 打赏
  • 举报
回复
select distinct a.* from test a join test b on a.a=b.a and a.id<>b.id
winternet 2005-02-18
  • 打赏
  • 举报
回复
select t.ID,t.a,t.b
from test as t
inner join
(select a from test group by a having count(a)>1)d
on t.a=d.a
子陌红尘 2005-02-18
  • 打赏
  • 举报
回复
select t.* from test t
where exists (select 1 from test where a = t.a and ID != t.id)
liricn 2005-02-18
  • 打赏
  • 举报
回复
上面的很好啊,可以揭帖了
hai2003xp 2005-02-18
  • 打赏
  • 举报
回复
也可以這樣

select a.* from test a ,(select a from test group by a having count(*)>1)b
where a.a=b.a
Softlee81307 2005-02-18
  • 打赏
  • 举报
回复
Create table test(id int,a int,b int)
insert into test
select 1,1,2 union all
select 2,1,3 union all
select 3,2,3 union all
select 4,2,3 union all
select 5,3,1 union all
select 6,4,1

----------------實現語句------------------

select * from test where a in
(select a from test group by a having count(*)>1)

--------------結果---------------------
ID a b
1 1 2
2 1 3
3 2 3
4 2 3
--------------------------------
drop table test ---------刪除測試
dzhfly 2005-02-18
  • 打赏
  • 举报
回复
支持楼上的
Softlee81307 2005-02-18
  • 打赏
  • 举报
回复
select * from test where a in
(select a from test group by a having count(*)>1)
bladewing 2005-02-18
  • 打赏
  • 举报
回复
自己顶

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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