查询结果集的sql疑惑?

wenle 2008-01-16 03:24:22
请问有两个表ta和tb 如下,现在要查询的结果集为
id a e
1 4 3
2 3 1
3 5 0

查询出来的e列为表ta表中id在tb表中b列大于2的记录条数
ta.id=tb.id

表ta
id a
1 4
2 3
3 5
表tb
id b
1 5
1 5
1 5
2 4
2 1
...全文
118 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
dobear_0922 2008-01-16
  • 打赏
  • 举报
回复
create table ta(id int, a int)
create table tb(id int, b int)

insert into ta values(1, 4 )
insert into ta values(2, 3 )
insert into ta values(3, 5 )

insert into tb values(1, 5 )
insert into tb values(1, 5 )
insert into tb values(1, 5 )
insert into tb values(2, 4 )
insert into tb values(2, 1 )

select a.id, a, e=isnull(b.e,0)
from ta a left join
(
select id , e=count(1) from tb where b>2 group by id
) b on a.id=b.id

/*
id a e
----------- ----------- -----------
1 4 3
2 3 1
3 5 0

(3 row(s) affected)
*/

drop table ta,tb
qiuming0306 2008-01-16
  • 打赏
  • 举报
回复
总是没有机会得分啊!
pt1314917 2008-01-16
  • 打赏
  • 举报
回复
create table ta(id int,a int)
insert into ta select 1,4
insert into ta select 2,3
insert into ta select 3,5

create table tb(id int,b int)
insert into tb select 1,5
insert into tb select 1,5
insert into tb select 1,5
insert into tb select 2,4
insert into tb select 2,1


select a.id,a.a,isnull(b.e,0)e from ta a left join
(select id,count(1)e from tb where b>2 group by id)b
on a.id=b.id
dawugui 2008-01-16
  • 打赏
  • 举报
回复
create table ta(id int, a int)
insert into ta values(1, 4 )
insert into ta values(2, 3 )
insert into ta values(3, 5 )
create table tb(id int, b int)
insert into tb values(1, 5 )
insert into tb values(1, 5 )
insert into tb values(1, 5 )
insert into tb values(2, 4 )
insert into tb values(2, 1)
go
select ta.id , ta.a , e = (select isnull(count(*),0) from tb where b > 2 and id = ta.id) from ta

drop table ta,tb

/*
id a e
----------- ----------- -----------
1 4 3
2 3 1
3 5 0

(3 行受影响)
*/
upingking 2008-01-16
  • 打赏
  • 举报
回复
select id ,a,( select count 1 from tb where ta.id=tb.id and b>2 ) as e from ta
free1879 2008-01-16
  • 打赏
  • 举报
回复
select a.id , a.a , e = (select isnull(count(*),0) from tb where b > 2 and id = a.id) from ta a
dawugui 2008-01-16
  • 打赏
  • 举报
回复
select ta.id , ta.a , e = (select isnull(count(*),0) from tb where b > 2 and id = ta.id) from ta
昵称被占用了 2008-01-16
  • 打赏
  • 举报
回复
select a.*,isnull(b.e,0) as e
from ta a left join (
select id ,count(1) as e from tb where b>2 group by id
) as b
on a.id=b.id
-狙击手- 2008-01-16
  • 打赏
  • 举报
回复
select a.id,a.a,e = select count(1) from tb where id = a.id and b > 2)
from a

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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