高手看下我的聚合代码该如何写?
SQL code
Declare@sqlvarchar(8000)select@sql='';select@sql='select departmentid,departmentname,staffid,staffname,monthid'select@sql=@sql+' ,isnull( ( select salaryreportitemresult from #TMPSRTR a where a.departmentid=#TMPSRTR.departmentid and a.staffid=#TMPSRTR.staffid and a.monthid=#TMPSRTR.monthid and a.ReportItemName='''+ reportitemname +''' ) ,0) as '+ reportitemname from CustomerSalaryReportItemsselect@sql=@sql+' , isnull( ( select sum(isnull(salaryreportitemresult,0)) from #TMPSRTR a where a.departmentid=#TMPSRTR.departmentid and a.staffid=#TMPSRTR.staffid and a.monthid=#TMPSRTR.monthid ),0) as 金额小计 'select@sql=@sql+' from #TMPSRTR group by departmentid,departmentname,staffid,staffname,monthid 'exec(@SQL)以上是一个动态的结果(相当于行转列吧)
下面是上面动态代码运行出来的一个结果,也就是动态代码中如果只有一列的情况
SQL code
select departmentid,departmentname,staffid,staffname,monthid ,isnull( ( select salaryreportitemresult from #TMPSRTR a where a.departmentid=#TMPSRTR.departmentid and a.staffid=#TMPSRTR.staffid and a.monthid=#TMPSRTR.monthid and a.ReportItemName='电费1' ),0) as 电费1from #TMPSRTR groupby departmentid,departmentname,staffid,staffname,monthid 现在我想要在上面的结果之上再进行按 departmentname 计算出小计求合及所有数据的总计列!
请各位指点!
GROUP BY WITH ROUPLE 得不到结果,用这个以后,数据列里面显示的是0(NULL) ,因为我的代码中不是SUM列
而想强加SUM时提示:
服务器: 消息 130,级别 15,状态 1,行 1
不能对包含聚合或子查询的表达式执行聚合函数。
我用的是SQL SERVER 2000