SQL Server 2008 R2-查询以按月销售总销售额和数量

时间:2013-11-01 17:39:32

标签: sql sql-server sql-server-2008

我有两张桌子STOCK和ITEMS,

我正在尝试获取一份报告,显示购买的商品总数(ITEMS table-items.quanto),商品的总销售额(ITEMS表 - 我假设(items.quanto * items.it_unlist)与描述(STOCK table-stock) .desc1)按月(ITEMS table-items.odr_date)分类(这是STOCK表中的一个字段 - stock.assoc)。

所有者希望2011年,2012年和2013年年度的每个月都有此信息

因此,2011年,2012年,2013年年初该项目的总销售额已售出总数量

这是我的查询

select items.item, items.quanto, SUM(items.QUANTO*items.it_unlist) as [total cost], stock.desc1, items.it_sdate from items
inner join
stock
on
stock.number = items.item
where IT_SDATE  between '2011-01-01 00:00:00.0' and '2011-12-31 00:00:00.0'
group by items.item, items.quanto, stock.desc1, items.it_sdate
order by IT_SDATE

我希望每个项目的总销量和数量按月计算,但这就是我自己想出来的......哈哈

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

select
  item,
  right(convert(varchar(8), it_sdate, 3), 5) theMonth,
  sum(quanto) totalQuantity,
  sum(quanto * it_unlist) totalSales,
  max(stock.desc1) descr,
  max(stock.assoc) assoc
from 
  items inner join stock on 
    items.item = stock.number
where
  it_sdate > '2011-01-01'
group by
  item,
  right(convert(varchar(8), it_sdate, 3), 5)
order by
  item,
  theMonth

http://sqlfiddle.com/#!3/246d3/18/0

答案 1 :(得分:0)

如果项目表的项目列是主键,那么当您尝试显示总销售额和数量时,则无法显示每个项目编号。 而且,IT_DATE列在表中每月只包含一个日期,那么只有下面的查询是可能的,否则我们需要编写其他查询。 如果没有,你可以选择。

select i.quanto, sum(QUANTO * it_unlist) as [total list], 
s.desc1, i.it_sdate from items i inner join stock s on (s.number = i.item)
where IT_SDATE > 2011-01-01
group by i.it_sdate order by IT_SDATE;