查询归属统计的问题。。

ideasky 2008-03-29 12:09:36
两个表,一个表存储问题,一个表存储答案,问题只有一条,答案可能对应有n条。
要查询出每个问题有多少个答案。
...全文
75 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
samson_www 2008-03-29
  • 打赏
  • 举报
回复
应该用外联结,因为可能有的问题没有答案
select a.questionid,isnull(b.answercount,0) as answer from questions a left join
(select count(1) as answercount from answers group by questionid) b
on a.questionid=b.questionid
viva369 2008-03-29
  • 打赏
  • 举报
回复
ls hao fast
liangCK 2008-03-29
  • 打赏
  • 举报
回复
select a.questionid,count(b.answser) cnt
from questions a
join answsers b
on a.questionid=b.questionid
group by a.questionid
  • 打赏
  • 举报
回复
同意3楼的,使用左外连接。
select questionid,count(answser)
from questions left join answsers on questions.questionid=answsers.questionid
group by questions.questionid
pengxuan 2008-03-29
  • 打赏
  • 举报
回复

create table a (id int identity(1,1),question varchar(36))
go
create table b (id int identity(1,1),aid int,answer varchar(36))
go

insert into a
select '中国的首都是哪个城市?' union all
select '你叫什么?'

insert into b
select 1,'上海' union all
select 1,'天津' union all
select 1,'深圳' union all
select 1,'北京' union all
select 2,'王五' union all
select 2,'张三' union all
select 2,'李四'

select * from a
select * from b

select a.question 问题,count(*) 答案数 from a inner join b on a.id=b.aid group by question
Aslan_ 2008-03-29
  • 打赏
  • 举报
回复
select 问题表.问题,isnull(count(答案表.答案ID),0) from 问题表 left join 答案表
on 问题表.问题ID = 答案表.问题ID

34,575

社区成员

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

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