一、生成统计数据的存储过程:
原码分享:
ALTER PROCEDURE [dbo].[zbysyy_cybrfyfltj] @startdate datetime,@enddate datetime AS
BEGIN SET NOCOUNT ON;
--从基础表中提取有用数据,结果放入临时表#a
select d.ksmc 科室名称, convert(nvarchar(10),b.jsrq,120) 结算日期, a.sfxmmc, a.sfje, b.zyh 住院号, c.brxm 姓名, b.fyze as 费用总计 into #a from zyjsmxb as a inner join zyjsgyb as b on a.jsdh=b.jsdh inner join zydjb as c on b.zyh=c.zyh inner join ksbmb as d on c.ryksbm=d.ksbm where b.jsrq between @startdate and @enddate and b.fyze!=0;
--将临时表#a中的数据由行转换为列,结果放入临时表#b
SELECT 科室名称, 结算日期, 住院号, 姓名, 费用总计, isnull(西药费,0) as 西药费, isnull(中成药,0) as 中成药, isnull(中草药,0) as 中草药, isnull(床位费,0) as 床位费, isnull(护理费,0) as 护理费, isnull(治疗费,0) as 治疗费, isnull(材料费,0) as 材料费, isnull(其他费,0) as 其他费, isnull(输氧费,0) as 输氧费, isnull(检查费,0) as 检查费, isnull(化验费,0) as 化验费, isnull(放射费,0) as 放射费, isnull(手术费,0) as 手术费, isnull(麻醉费,0) as 麻醉费 into #b FROM #a pivot ( sum(sfje) for sfxmmc in (西药费,中成药,中草药,床位费,护理费,治疗费,材料费,其他费, 输氧费,检查费,化验费,放射费,手术费,麻醉费) ) as tbl order by 科室名称,结算日期,住院号;
--假如表zbysyy_cybrfyfltjb存在,那么删除该表
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[zbysyy_cybrfyfltjb]') AND type in (N'U')) DROP TABLE [dbo].[zbysyy_cybrfyfltjb];
--生成小计行、合计行,最终结果放入永久表zbysyy_cybrfyfltjb中
SELECT rtrim(ltrim(科室名称)) as 科室名称, 住院号+'/'+ 姓名+'/'+结算日期 结算信息, sum(费用总计) as 费用总计, sum(西药费) as 西药费, sum(中成药) as 中成药, sum(中草药) as 中草药, sum(床位费) as 床位费, sum(护理费) as 护理费, sum(治疗费) as 治疗费, sum(材料费) as 材料费, sum(其他费) as 其他费, SUM(输氧费) as 输氧费, sum(检查费) as 检查费, sum(化验费) as 化验费, sum(放射费) as 放射费, sum(手术费) as 手术费, sum(麻醉费) as 麻醉费 into zbysyy_cybrfyfltjb FROM #b group by rtrim(ltrim(科室名称)) , 住院号+'/'+ 姓名+'/'+结算日期 with rollup;
--更新科室小计行的结算信息列的列值为小计
update zbysyy_cybrfyfltjb set 结算信息='小计' where 科室名称 is not null and 结算信息 is null;
--更新合计行的科室名称列的列值为合计
update zbysyy_cybrfyfltjb set 科室名称='合计' ,结算信息='' where 科室名称 is null and 结算信息 is null;
--显示最终表的结果
select * from zbysyy_cybrfyfltjb;
--删除临时表#a,#b drop table #a,#b;
END
二、存储过程的运行结果:
原创作品,转载请注明出处!
2019年10月18日于山东淄博