通过写《费用明细表》发现写sql的乐趣

declare @strsql varchar(max)
declare @strsql1 varchar(max)
declare @strsql2 varchar(max) = ''

set @strsql =
'select * from
(select distinct
case when (select count(*) from syscolumns where id = object_id(''门诊_发票明细表''))=''20'' then ''门诊''
else ''住院'' end as 费用类型,
a.收费日期 as 发生日期,
a.姓名 as 患者姓名,
b.shbzhm as 患者编号,
b.ylrylb 患者医保类型,
case when b.yfdxbz=''济南'' then ''济南'' else ''济南'' end as 居民医保区域,
d.类别名称 as 结算项目类别,
e.医保编码 as 结算项目编码,
e.项目名称 as 结算项目名称,
c.数量 as 数量,
c.单位 as 单位,
c.单价 as 单价,
(c.报销金额+c.自费金额+c.减免金额) as 总金额,
c.报销金额 as 医保报销,
c.自费金额 as 自付,
c.减免金额 as 其他拨付 '

set @strsql1 = 'from 济南_医保收费表 a
left join 济南_医保帐户表 b on a.门诊号=b.门诊号
left join 门诊_发票明细表 c on a.发票编号=c.发票编号
left join 代码_项目类别表 d on c.项目类别=d.项目类别
left join 代码_收费项目表 e on e.项目类别=c.项目类别 and e.项目代码=c.项目代码
union all
select
distinct case when (select count(*) from syscolumns where id = object_id(''住院_发票明细表''))=''24'' then ''住院'' else ''门诊'' end as 费用类型,
a.收费日期 as 发生日期,
a.姓名 as 患者姓名,
b.shbzhm as 患者编号,
b.ylrylb 患者医保类型,
case when b.yfdxbz=''济南'' then ''济南'' else ''济南'' end as 居民医保区域,
d.类别名称 as 结算项目类别,
e.医保编码 as 结算项目编码,
e.项目名称 as 结算项目名称,
c.数量 as 数量,
c.单位 as 单位,
c.单价 as 单价,
(c.报销金额+c.自费金额+c.减免金额) as 总金额,
c.报销金额 as 医保报销,
c.自费金额 as 自付,
c.减免金额 as 其他拨付
from 济南_医保收费表 a
left join 济南_医保帐户表 b on a.门诊号=b.门诊号
left join 住院_发票明细表 c on a.发票编号=c.发票编号
left join 代码_项目类别表 d on c.项目类别=d.项目类别
left join 代码_收费项目表 e on e.项目类别=c.项目类别 and e.项目代码=c.项目代码
) as A
where A.发生日期 between '+''''+ @开始时间 +''''+' and '+ +''''+@结束时间+'''' +' '

if( @费用类型<> '')
set @strsql2 =@strsql2+ ' and A.费用类型 in ( '+''''+@费用类型+''''+') '
if( @医保类型 <> '')
set @strsql2 =@strsql2+ ' and A.患者医保类型 in ('+''''+ @医保类型+''''+') '
if( @患者姓名 <> '')
set @strsql2 =@strsql2+ ' and A.患者姓名 in ('+''''+ @患者姓名+''''+') '
if( @结算项目类型 <> '')
set @strsql2 =@strsql2+ ' and A.结算项目类别 in ('+''''+ @结算项目类型+''''+')'

exec (@strsql + @strsql1 + @strsql2)

原文地址:https://www.cnblogs.com/hushzhang/p/6699395.html