请问 sqlserver 各个商品各月销售额统计 sql语句怎么写????

表结构:oid 流水号,pid 商品编码,date 销售日期,count 销售数量
现在要统计各个商品的年销售额 各月销售额
希望结果:
商品编码 年销售额 一月销售额 二月销售额 ........ 十二月销售额
单独统计出来各列很简单 ,请问如何在sql里生成上面的表结构?

可以完成,思路如下:

通过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 指的就是销售日期[月],最后还有一列为年度总计

希望能帮到你!

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-08-15
;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

看看是否你要的结果 

本回答被提问者采纳
相似回答