select 年月,部门,姓名,编号,
sum(case when PayId<>'21' and 年月='201401' then (select sfgz from b a where right(年月,2)='01' And PayId<>'21' and 编号=b.编号) end ) '一月',
sum(case when PayId<>'21' and 年月='201402' then (select sfgz from b a where right(年月,2)='02' And PayId<>'21' and 编号=b.编号) end ) '二月',
sum(case when PayId<>'21' and 年月='201403' then (select sfgz from b a where right(年月,2)='03' And PayId<>'21' and 编号=b.编号) end ) '三月',
sum(case when PayId<>'21' and 年月='201404' then (select sfgz from b a where right(年月,2)='04' And PayId<>'21' and 编号=b.编号) end ) '四月',
sum(case when PayId<>'21' and 年月='201405' then (select sfgz from b a where right(年月,2)='05' And PayId<>'21' and 编号=b.编号) end ) '五月',
sum(case when PayId<>'21' and 年月='201406' then (select sfgz from b a where right(年月,2)='06' And PayId<>'21' and 编号=b.编号) end ) '六月',
sum(case when PayId<>'21' and 年月='201407' then (select sfgz from b a where right(年月,2)='07' And PayId<>'21' and 编号=b.编号) end ) '七月',
sum(case when PayId<>'21' and 年月='201408' then (select sfgz from b a where right(年月,2)='08' And PayId<>'21' and 编号=b.编号) end ) '八月',
sum(case when PayId<>'21' and 年月='201409' then (select sfgz from b a where right(年月,2)='09' And PayId<>'21' and 编号=b.编号) end ) '九月',
sum(case when PayId<>'21' and 年月='201410' then (select sfgz from b a where right(年月,2)='10' And PayId<>'21' and 编号=b.编号) end ) '十月',
sum(case when PayId<>'21' and 年月='201411' then (select sfgz from b a where right(年月,2)='11' And PayId<>'21' and 编号=b.编号) end ) '十一月',
sum(case when PayId<>'21' and 年月='201412' then (select sfgz from b a where right(年月,2)='12' And PayId<>'21' and 编号=b.编号) end ) '十二月'
from b,c
where c.id=b.id
and left(年月,4)='2014'
and 编号='18'
消息 130,级别 15,状态 1,第 3 行
不能对包含聚合或子查询的表达式执行聚合函数。
消息 130,级别 15,状态 1,第 4 行
不能对包含聚合或子查询的表达式执行聚合函数。
消息 130,级别 15,状态 1,第 5 行
不能对包含聚合或子查询的表达式执行聚合函数。
消息 130,级别 15,状态 1,第 6 行
------解决思路----------------------
坦率的说,没太看明白,试试:
select 年月,部门,姓名,编号,
sum(case when 年月='201401' then sfgz else 0 end ) as '一月',
sum(case when 年月='201402' then sfgz else 0 end ) as '二月',
sum(case when 年月='201403' then sfgz else 0 end ) as '三月',
sum(case when 年月='201404' then sfgz else 0 end ) as '四月',
sum(case when 年月='201405' then sfgz else 0 end ) as '五月',
sum(case when 年月='201406' then sfgz else 0 end ) as '六月',
sum(case when 年月='201407' then sfgz else 0 end ) as '七月',
sum(case when 年月='201408' then sfgz else 0 end ) as '八月',
sum(case when 年月='201409' then sfgz else 0 end ) as '九月',
sum(case when 年月='201410' then sfgz else 0 end ) as '十月',
sum(case when 年月='201411' then sfgz else 0 end ) as '十一月',
sum(case when 年月='201412' then sfgz else 0 end ) as '十二月'
from
b,c
where
b.编号=c.编号
and
c.id=b.id
and
left(年月,4)='2014'
and
b.编号='18'
and
PayId<>'21'
group by
年月,部门,姓名,编号