27,579
社区成员
发帖
与我相关
我的任务
分享
现有销售维修表A 字段是 商品名 生产日期 销售日期 维修日期
现在要统计2012年10月到2013年3月 每个月销售出去的商品在4个月内发生维修汇总。
例如:2012年10月卖出了10个商品
2012年11月有2条维修的记录
2012年12月有3条维修的记录
2013年1月有0条维修的记录
那2012年10月卖出的商品在四个月内发生维修的总合就是5。
只对月份进行计算用DATEDIFF(mm,维修日期,销售日期)<=4做为统计条件
最后要按每个月进行分组.
显示结果样例:
统计月份 4个月内维修汇总
2012年10月 5
2012年11月 0
2012年12月 1
2013年1月 10
2013年2月 20
2013年3月 100
select rtrim(year(a.销售日期))+'年'+rtrim(month(a.销售日期))+'月' '统计月份',
(select count(1) from 销售维修表A b
where datediff(m,a.销售日期,b.维修日期) between 0 and 4
and datediff(m,a.销售日期,b.销售日期)=0) '4个月内维修汇总'
from 销售维修表A a
where a.销售日期 between '2012-10-01' and '2013-03-31'
group by year(a.销售日期),month(a.销售日期)
select rtrim(year(a.销售日期))+'年'+rtrim(month(a.销售日期))+'月' '统计月份',
(select count(1) from 销售维修表A b
where isnull(datediff(m,a.销售日期,b.维修日期),0) between 0 and 4 --维修日期为空时
and datediff(m,a.销售日期,b.销售日期)=0) '4个月内维修汇总'
from 销售维修表A a
where a.销售日期 between '2012-10-01' and '2013-03-31'
group by year(a.销售日期),month(a.销售日期)