今天遇到一个问题
这是下面的例句:
select (select count(b1.name) from table_b where a1.id=b1.id
and ···)from table_1 a1 where ···
大致就是这样的一个句子
但是最后返回的count()居然不是一个值,而是一个很多结果的集合
正常的select count() from table where ···返回的就是一个值啊?
为什么这么写呢?有什么意义呢?
下面创建俩个表
表#a_aa_a、#a_aa_b
create table #a_aa_a(
t_id int,
t_name varchar(10),
t_date int,
t_grade int
)
insert into #a_aa_a VALUES (132154,'盲僧',20210401,1)
insert into #a_aa_a VALUES (231654,'盲僧',20210403,2)--
insert into #a_aa_a VALUES (236587,'盲僧',20210405,3)
insert into #a_aa_a VALUES (365214,'亚索',20210401,1)
insert into #a_aa_a VALUES (365214,'亚索',20210403,2)--
insert into #a_aa_a VALUES (325412,'亚索',20210405,3)
insert into #a_aa_a VALUES (365584,'盖伦',20210401,1)
insert into #a_aa_a VALUES (236587,'盖伦',20210403,2)--
insert into #a_aa_a VALUES (326985,'盖伦',20210408,3)
create table #a_aa_b(
t_id int,
t_name varchar(10),
t_grade int
)
insert into #a_aa_b VALUES (132154,'盲僧',3)
insert into #a_aa_b VALUES (231654,'盲僧',8)
insert into #a_aa_b VALUES (236587,'盲僧',6)
insert into #a_aa_b VALUES (365214,'亚索',5)
insert into #a_aa_b VALUES (365214,'亚索',2)--
insert into #a_aa_b VALUES (325412,'亚索',1)
insert into #a_aa_b VALUES (365584,'盖伦',10)
insert into #a_aa_b VALUES (236587,'盖伦',2)--
insert into #a_aa_b VALUES (326985,'盖伦',23)
按上述例子,得到相同情景下的select嵌套语句
select (select count(t_id) from #a_aa_b b where a.t_name = b.t_name
and a.t_grade=b.t_grade ) from #a_aa_a a where t_grade=2
经过试验,其实这个嵌套语句的功能就是分组,类似于group by b.t_id,为什么说是类似呢,因为group by 语句是不会返回空的值的,为空的数据不会显示,但是select嵌套语句会显示出来
与上述语句同等力效的语句
select count(b.t_id) from #a_aa_b b inner join #a_aa_a a
on a.t_name = b.t_name and a.t_grade=b.t_grade and a.t_grade=2 group by a.t_id
俩语句结果对比--(筛选数据为创建表语句后面有--的数据)
select嵌套语句结果图:
常规group by语句结果图
不需要计算为0数据情况,二者皆可使用