a表老师学生对应,有老师字段,一个老师对应多个学生
b表学生书本,学生字段,一个学生对应多本书老师 学生
A a
A b
B c
C d
B e
学生 书本
a 书名1
a 书名2
b 书名3
c 书名4
d 书名5
d 书名6
e 书名7
请问一下应该怎么写统计出来应该A老师下的学生拥有书本 3 本
B老师下的学生拥有书本 2 本
C老师下的学生拥有书本 2 本
b表学生书本,学生字段,一个学生对应多本书老师 学生
A a
A b
B c
C d
B e
学生 书本
a 书名1
a 书名2
b 书名3
c 书名4
d 书名5
d 书名6
e 书名7
请问一下应该怎么写统计出来应该A老师下的学生拥有书本 3 本
B老师下的学生拥有书本 2 本
C老师下的学生拥有书本 2 本
from tb1 a,tb2 b
where a.学生=b.学生
group by a.老师
insert @tb1 select 'A' , 'a'
insert @tb1 select 'A' , 'b'
insert @tb1 select 'B' , 'c'
insert @tb1 select 'C' , 'd'
insert @tb1 select 'B' , 'e' declare @tb2 table(学生 varchar(10),书本 varchar(10))
insert @tb2 select 'a' , '书名1'
insert @tb2 select 'a' , '书名2'
insert @tb2 select 'b' , '书名3'
insert @tb2 select 'c' , '书名4'
insert @tb2 select 'd' , '书名5'
insert @tb2 select 'd' , '书名6'
insert @tb2 select 'e' , '书名7' select a.老师+'老师下的学生拥有书本' des, ltrim(count(b.学生))+'本' cnt
from @tb1 a,@tb2 b
where a.学生=b.学生
group by a.老师/*
des cnt
------------------------------ --------------
A老师下的学生拥有书本 3本
B老师下的学生拥有书本 2本
C老师下的学生拥有书本 2本(所影响的行数为 3 行)
*/
select t,count(k)as j from
(select a.t,b.s,b.k from a,b where a.s=b.s)c
group by t)h
create table a
(t Nvarchar(10),s Nvarchar(10))
create table b
(s Nvarchar(10),k Nvarchar(10))
insert a values('A','a')
insert a values('A','b')
insert a values('B','c')
insert a values('C','d')
insert a values('B','e')insert b values('a','书名2')
insert b values('b','书名3')
insert b values('a','书名1')
insert b values('c','书名4')
insert b values('d','书名5')
insert b values('d','书名6')
insert b values('e','书名7')
*/
select t+'老师下的学生拥有书本'+convert(char(2),j)+'本'as 统计 from
(select a.t,count(b.k)as j from a,b where a.s=b.s group by a.t )h
create table t1(老师 varchar(10), 学生 varchar(10))
go
create table t2(学生 varchar(10), 书本 varchar(10))
go
insert into t1
select 'A','a' union all
select 'A','b' union all
select 'B','c' union all
select 'C','d' union all
select 'B','e'
go
insert into t2
select 'a','书名1' union all
select 'a','书名2' union all
select 'b','书名3' union all
select 'c','书名4' union all
select 'd','书名5' union all
select 'd','书名6' union all
select 'e','书名7' select t1.老师+'下的学生拥有书本'+cast(count(*) as varchar(10))+'本' from t1 inner join t2 on t1.学生=t2.学生 group by t1.老师
from 和t1 a left outer join t2 b on a.学生=b.学生 group by a.老师