case when then 随手练_1

时间:2025-05-15 20:36:56

CASE WHEN THEN随手练,就当做练习指法吧

--drop table tbStudent
GO
Create table tbStudent(
studentId int identity(1,1),
fSex varchar(12),
fProvince varchar(32)
)
GO
INSERT INTO tbStudent(fsex,fProvince)
values('男','江西省'),
('男','广东省'),
('男','浙江省'),
('女','江西省'),
('男','浙江省'),
('女','浙江省')
select *
from tbStudent
---------------------------------------------------------------------
--要查出:江西、广东、浙江 男女个数
select fSex,
count(case when fProvince='江西省' then '江西省' end) as 江西省,
count(case when fProvince='广东省' then '江西省' end) as 广东省,
count(case when fProvince='浙江省' then '江西省' end) as 浙江省
from tbStudent
group by fSex
---------------------------------------------------------------------
--要查出:江西、广东、浙江 男女个数
select fSex,
count(case fProvince when '江西省' then '江西省' end) as 江西省,
count(case fProvince when '广东省' then '江西省' end) as 广东省,
count(case fProvince when '浙江省' then '江西省' end) as 浙江省
from tbStudent
group by fSex
--------------------------------------------------------------------- ---------------------------------------------------------------------

运行结果:select * from tbStudent                        CASE WEHN THEN之后

case when then 随手练_1                                         case when then 随手练_1