日期:2014-05-18  浏览次数:20505 次

单表中的查询
一个表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 班号,班级人数,迟到人数,未迟到人数