SQL查询以从学生和分数表中获取数据
我有两张桌子和两本书 学生:sid编号,sname varchar3SQL查询以从学生和分数表中获取数据,sql,sql-server,Sql,Sql Server,我有两张桌子和两本书 学生:sid编号,sname varchar3 sid sname --------- 4 abc 2 def 1 ghi 3 jkl 图书:sid编号,图书varchar1 sid book --------- 3 a 2 b 2 c 1 u 4 d 1 k 3 p 4 q 4 k 现在,我想要如下所示的输出sid、sname和每个学生阅读的书籍数量 sid sname
sid sname
---------
4 abc
2 def
1 ghi
3 jkl
图书:sid编号,图书varchar1
sid book
---------
3 a
2 b
2 c
1 u
4 d
1 k
3 p
4 q
4 k
现在,我想要如下所示的输出sid、sname和每个学生阅读的书籍数量
sid sname count
---------------
1 ghi 2
2 def 2
3 jkl 2
4 abc 3
请帮我解决这个问题。只需在sid列中加入两个
请尝试此查询一次
select * into #student from(
select 4 s_id,'abc' as name
union all
select 2 ,'def'
union all
select 1 ,'ghi'union all
select 3 ,'jkl'
) as a
drop table #student
select * into #books from(
select 3 s_id,'a' as book
union all
select 2 ,'b'
union all
select 2 , 'c'union all
select 1 , 'u'union all
select 4 , 'd'union all
select 1 ,'k'union all
select 3 ,'p'union all
select 4 ,'q'union all
select 4 ,'k'
) as a
select * from #student
select * from #books
select s.s_id,s.name,COUNT(b.s_id) as[count] from #student s
inner join #books b on b.s_id=s.s_id
group by s.s_id,s.name
结果输出如下
+------+------+-------+
| s_id | name | count |
+------+------+-------+
| 1 | ghi | 2 |
| 2 | def | 2 |
| 3 | jkl | 2 |
| 4 | abc | 3 |
+------+------+-------+
`选择sname,cnt from students s join选择sid,按s.sid=b.sid;上的sid b将*计为cnt from books group好吗?@Raaki你在评论中提出了不完整的问题,但我明白了。您希望先聚合,然后加入。它将产生与学生表相同的结果,或者至少应该有唯一的学生。只是键入@GurV。现在请检查完整的结果query@Raaki这将与我的查询做相同的事情。最好在代码中包含一些上下文/解释,因为这会使答案对OP和未来的读者更有用。您可以随时编辑你的问题没有得到回答吗?
select * into #student from(
select 4 s_id,'abc' as name
union all
select 2 ,'def'
union all
select 1 ,'ghi'union all
select 3 ,'jkl'
) as a
drop table #student
select * into #books from(
select 3 s_id,'a' as book
union all
select 2 ,'b'
union all
select 2 , 'c'union all
select 1 , 'u'union all
select 4 , 'd'union all
select 1 ,'k'union all
select 3 ,'p'union all
select 4 ,'q'union all
select 4 ,'k'
) as a
select * from #student
select * from #books
select s.s_id,s.name,COUNT(b.s_id) as[count] from #student s
inner join #books b on b.s_id=s.s_id
group by s.s_id,s.name
+------+------+-------+
| s_id | name | count |
+------+------+-------+
| 1 | ghi | 2 |
| 2 | def | 2 |
| 3 | jkl | 2 |
| 4 | abc | 3 |
+------+------+-------+