表1的内容:
日期 类别 数量 医生
2006-1-1 中药 3 A
2006-1-1 西药 5 A
2006-1-1 中药 2 B
2006-1-1 西药 2 B
2006-1-2 中药 3 A
2006-1-2 西药 5 A
2006-1-2 中药 2 B
2006-1-2 西药 2 B
.....
要求得到这样的结果:
类别 中药 西药
本月总计: 10 14
其中:医生A 5 7
医生B 5 7
.....
日期 类别 数量 医生
2006-1-1 中药 3 A
2006-1-1 西药 5 A
2006-1-1 中药 2 B
2006-1-1 西药 2 B
2006-1-2 中药 3 A
2006-1-2 西药 5 A
2006-1-2 中药 2 B
2006-1-2 西药 2 B
.....
要求得到这样的结果:
类别 中药 西药
本月总计: 10 14
其中:医生A 5 7
医生B 5 7
.....
sum(case 类别 when '中药' then 数量 else 0 end) as 中药,
sum(case 类别 when '西药' then 数量 else 0 end) as 西药
from 表1
where 日期 between '2006-1-1' and '2006-1-31'
union all
select '其中:医生'+医生 as 类别,
sum(case 类别 when '中药' then 数量 else 0 end) as 中药,
sum(case 类别 when '西药' then 数量 else 0 end) as 西药
from 表1
where 日期 between '2006-1-1' and '2006-1-31'
group by 医生
insert test select '2006-1-1','中药',3,'A'
union all select '2006-1-1','西药',5,'A'
union all select '2006-1-1','中药',2,'B'
union all select '2006-1-1','西药',2,'B'
union all select '2006-1-2','中药',3,'A'
union all select '2006-1-2','西药',5,'A'
union all select '2006-1-2','中药',2,'B'
union all select '2006-1-2','西药',2,'B'
select * from testselect 类别='总计',sum(case 类别 when '中药' then 数量 else 0 end) 中药,
sum(case 类别 when '西药' then 数量 else 0 end) 西药
from test
union all
select 类别='医生A',sum(case when 类别='中药' and 医生='A' then 数量 else 0 end) 中药,
sum(case when 类别='西药' and 医生='A' then 数量 else 0 end) 西药
from test
union all
select 类别='医生B',sum(case when 类别='中药' and 医生='B' then 数量 else 0 end) 中药,
sum(case when 类别='西药' and 医生='B' then 数量 else 0 end) 西药
from test