首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

单表中的查询解决办法

2012-02-21 
单表中的查询一个表table0其下有三个属性:班号、学生ID、迟到否!createTabletable0(班号varchar(10),学生IDi

单表中的查询
一个表table0   其下有三个属性:班号、学生ID、迟到否!
create     Table   table0
(
  班号   varchar(10),
  学生ID   int,
迟到否   bit,
)
要求查询得到:
班号     班级人数     迟到人数     未迟到人数


[解决办法]
select 班号,count(*) 班级人数,
sum(case when 迟到否=0 then 1 else 0 end) 迟到人数,
sum(case when 迟到否=1 then 1 else 0 end) 未迟到人数
from table0
group by 班号
[解决办法]
select 班号,sum(1) as 班级人数,sum(case 迟到否 when 1 then 1 else 0 end) as 迟到人数,sum(case 迟到否 when 0 then 1 else 0 end) as 未迟到人数 from table0 group by 班号
[解决办法]
create Table table0
(
班号 varchar(10),
学生ID int,
迟到否 bit,
)
要求查询得到:
班号 班级人数 迟到人数 未迟到人数
select
班号,
班级人数 = (select count(*) from table0 where 班号=a.班号),
迟到人数 = (select count(*) from table0 where 班号=a.班号 and 迟到否=true),
未迟到人数 = (select count(*) from table0 where 班号=a.班号 and 迟到否=false)
from table0 a group by 班级人数,迟到人数,未迟到人数
[解决办法]
select
班号,
班级人数 = (select count(*) from table0 where 班号=a.班号),
迟到人数 = (select count(*) from table0 where 班号=a.班号 and 迟到否=true),
未迟到人数 = (select count(*) from table0 where 班号=a.班号 and 迟到否=false)
from table0 a group by 班号,班级人数,迟到人数,未迟到人数

热点排行