日期:2014-05-18 浏览次数:20451 次
if object_id('[tb]') is not null drop table [tb] go create table [tb]([CXRQ] varchar(8),[KB] varchar(8),[LB] varchar(4),[JE] numeric(6,2)) insert [tb] select '20110419','急诊科','1300',168.09 union all select '20110720','专家门诊','1602',420.00 union all select '20110919','专家门诊','1502',500.61 union all select '20110925','大内科','1600',160.00 union all select '20110607','普外科','1302',13.38 union all select '20110810','城北康','1600',160.00 union all select '20120106','口腔科','1301',2.70 union all select '20110426','内科门诊','1301',1594.24 union all select '20110504','急诊科','1616',220.00 union all select '20111115','专家门诊','1601',412.00 union all select '20110308','内科门诊','1601',264.00 union all select '20110721','口腔科','1300',1.47 union all select '20110323','体检中心','1606',170.00 union all select '20110616','脑外科','1505',39.00 union all select '20110919','大内科','1505',283.50 union all select '20110310','专家门诊','1400',2480.08 union all select '20110212','脑外科','1604',25.00 go -->数据查询: declare @sql varchar(8000) select @sql=isnull(@sql+',','') +'sum(case when kb='''+kb+''' then je else 0 end) as ['+kb+']' from (select distinct kb from tb) t exec ('select isnull(cxrq,''合计'') as [类别],' +@sql +',sum(je) as [合计] from tb group by cxrq with rollup' ) /** 类别 城北康 大内科 急诊科 口腔科 内科门诊 脑外科 普外科 体检中心 专家门诊 合计 -------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- 20110212 0.00 0.00 0.00 0.00 0.00 25.00 0.00 0.00 0.00 25.00 20110308 0.00 0.00 0.00 0.00 264.00 0.00 0.00 0.00 0.00 264.00 20110310