条件加在where 和on后面的特殊比较

本文通过一个具体例子展示了如何使用SQL进行复杂的数据查询与统计,特别是针对特定条件下的分组计数,对比了不同条件下查询结果的变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-- 条件加在where on后面的特殊比较

-- 查找满足班级为102,班的男女生人数,要求年龄大于等于

 

set nocount on

if object_id('Students') is not null

drop table Students;

 

create table Students

(

StudentNo varchar(50), --学号

ClassNo varchar(50), --班级

Gender INT, --性别0:女1:男

Age INT  --年龄

)

go

 

 

if object_id('Genders') is not null

drop table Genders;

 

create table Genders

(

    Gender INT,

    GenerName VARCHAR(20)

)

go

insert into Genders values(0, '')

insert into Genders values(1, '')

 

 

go

insert into Students values('00001', '101', 1, 8);

insert into Students values('00002', '101', 1, 8);

insert into Students values('00003', '101', 0, 8);

insert into Students values('00004', '101', 1, 8);

insert into Students values('00005', '101', 0, 8);

 

insert into Students values('00006', '102', 0, 11);

insert into Students values('00007', '102', 1, 11);

insert into Students values('00008', '102', 0, 11);

insert into Students values('00009', '102', 1, 11);

insert into Students values('00010', '102', 0, 11);

 

insert into Students values('00011', '103', 1, 10);

insert into Students values('00012', '103', 1, 10);

insert into Students values('00013', '103', 1, 10);

insert into Students values('00014', '103', 1, 10);

insert into Students values('00015', '103', 1, 10);

GO

 

 

select c.ClassNo,c.GenerName,num= count(d.Gender) 

from

(

    select distinct ClassNo,GenerName,b.Gender  from Students a

    cross join Genders b

)c

left join Students d on c.ClassNo=d.ClassNo and c.Gender=d.Gender and age>=10

where

    c.classno in ('102', '103') --and age>=10

group by c.ClassNo,c.GenerName

order by c.ClassNo

 

 

-- 加在ON

ClassNo                                            GenerName            num

-------------------------------------------------- -------------------- -----------

102                                                                   2

102                                                                   3

103                                                                   5

103                                                                   0

 

--加在WHERE

 

ClassNo                                            GenerName            num

-------------------------------------------------- -------------------- -----------

102                                                                   2

102                                                                   3

103                                                                   5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值