可以完成,思路如下:
通过pid 商品编码分组,得到销售日期的每个月列,后用sum(case Fact_m WHEN 月份 then 数量end)来操作即可.
--年度售额:
select pid 商品编码
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '01' then cCost end)),0) 'countCost_1'
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '02' then cCost end)),0) 'countCost_2'
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '03' then cCost end)),0) 'countCost_3'
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '04' then cCost end)),0) 'countCost_4'
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '05' then cCost end)),0) 'countCost_5'
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '06' then cCost end)),0) 'countCost_6'
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '07' then cCost end)),0) 'countCost_7'
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '08' then cCost end)),0) 'countCost_8'
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '09' then cCost end)),0) 'countCost_9'
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '10' then cCost end)),0) 'countCost_10'
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '11' then cCost end)),0) 'countCost_11'
,isnull(convert(dec(18,2),sum(case Fact_m WHEN '12' then cCost end)),0) 'countCost_12'
,isnull(convert(dec(18,2),sum(cCost))) 'countTotal'
from Tab group by pid
--Fact_m 指的就是销售日期[月],最后还有一列为年度总计
希望能帮到你!
;with cte_tot as(
select PID,sum(count) totalmoney,convert(varchar(10),month(date))+'月' date
from 数据表 with(nolock) where date between '2013-01-01' and '2013-08-15' group by PID,month(date) )
select PID, sum(totalmoney) as totalmoney, sum(case date when '1月' then totalmoney else null end) as '1月' ,
sum(case date when '2月' then totalmoney else null end) as '2月' ,
sum(case date when '3月' then totalmoney else null end) as '3月' ,
sum(case date when '4月' then totalmoney else null end) as '4月' ,
sum(case date when '5月' then totalmoney else null end) as '5月' ,
sum(case date when '6月' then totalmoney else null end) as '6月' ,
sum(case date when '7月' then totalmoney else null end) as '7月' ,
sum(case date when '8月' then totalmoney else null end) as '8月' ,
sum(case date when '9月' then totalmoney else null end) as '9月' ,
sum(case date when '10月' then totalmoney else null end) as '10月' ,
sum(case date when '11月' then totalmoney else null end) as '11月' ,
sum(case date when '12月' then totalmoney else null end) as '12月'
from cte_tot group by PID
看看是否你要的结果