当前位置: 代码迷 >> Sql Server >> 请问统计本月金额和上月金额
  详细解决方案

请问统计本月金额和上月金额

热度:43   发布时间:2016-04-24 18:16:02.0
请教统计本月金额和上月金额
请教统计本月金额和上月金额:
有货物名称,规格,数量,单价,金额
需要统计出本月金额,上月金额
SQL语句怎么写?高手请指教
------解决方案--------------------

declare @y int,@m int
select @y=2013,@m=6  --> 指定当前月是2013年6月

select 货物,规格,数量,单价,
            (select sum(金额) 
             from [表名] b 
             where b.货物=a.货物 and b.规格=a.规格 and datediff(mm,b.日期,cast(rtrim(@y)+'-'+rtrim(@m)+'-01' as datetime))=0) '本月金额',
            (select sum(金额) 
             from [表名] b 
             where b.货物=a.货物 and b.规格=a.规格 and datediff(mm,b.日期,cast(rtrim(@y)+'-'+rtrim(@m)+'-01' as datetime))=1) '上月金额'
 from [表名] a
 group by 货物,规格,数量,单价
  相关解决方案