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

一道sql面试题,真难,你会不???????
题目一、

SQL Server中有如下表,用sql统计出某一时间段内门诊与住院的检查人数与费用
表:reg_info{sheetid,patientType,ExamDateTime,fee}
表字段说明:
  Sheetid varchar(32)-- 检查号(表明是一次检查),主键
  PatientType char(1)-- 病人类别:0代表门诊,1代表住院
  ExamDateTime datetime--检查时间
  fee decimal(8,2) -- 检查费用

例:

(07年12月——08年6月)数据如下

月份 门诊人数 门诊费用 住院人数 住院费用
12 1 10 2 20
1 1 10 2 20
2 2 20 2 20
3 1 10 2 20
4 4 40 2 20
5 1 10 2 20
6 1 10 2 20


会吗?

------解决方案--------------------
SQL code
select datename(mm,ExamDateTime) as 月份,
sum(case when PatientType=0 then 1 else 0 end) as 门诊人数,
sum(case when PatientType=0 then fee else 0 end) as 门诊费用,
sum(case when PatientType=1 then 1 else 0 end) as 住院人数,
sum(case when PatientType=1 then fee else 0 end) as 住院费用
from 表
where 查询条件=.....
group by datename(mm,ExamDateTime)

------解决方案--------------------
SQL code
select 
  convert(varchar(7),ExamDateTime,120) as 月份,
  sum(case when PatientType=0 then 0 else 0 end) as 门诊人数,
  sum(case when PatientType=0 then fee else 0 end) as 门诊费用,
  sum(case when PatientType=0 then 1 else 0 end) as 住院人数,
  sum(case when PatientType=0 then fee else 0 end) as 住院费用
from
  reg_info
where
  convert(varchar(7),ExamDateTime,120) between '2007-12' and '2008-06'
group by
  convert(varchar(7),ExamDateTime,120)