改一点 select *, 前6个月销量=(select sum(销量) from t where 产品类型=a.产品类型 and datediff(month,销售日期,a.销售日期)<=6) from t a
添加一个字段后,用下面的语句修改数据 update a set a.前6个月销量 = (select sum(销量) from tablename where 产品类型 = a.产品类型 and datediff(month, cast(a.销售日期 + '-01' as datetime), cast(销售日期 + '-01' as datetime) < 7) from tablename a
--前6个月应该用 between ,否则计算的结果会有问题select * ,前6个月销量=( select sum(销量) from 表 where 产品类型=a.产品类型 and datediff(month,销售日期+'-1',a.销售日期+'-1') between 1 and 6) from 表 a
select *,
前6个月销量=(select sum(销量)
from t
where 产品类型=a.产品类型
and datediff(month,销售日期,a.销售日期)<=6)
from t a
update a
set a.前6个月销量 = (select sum(销量)
from tablename
where 产品类型 = a.产品类型
and datediff(month, cast(a.销售日期 + '-01' as datetime),
cast(销售日期 + '-01' as datetime) < 7)
from tablename a
,前6个月销量=(
select sum(销量) from 表
where 产品类型=a.产品类型
and datediff(month,销售日期+'-1',a.销售日期+'-1') between 1 and 6)
from 表 a
否则计算出来的是从前6月开始的所有数据(包括当月和之后的全部数据)邹老大厉害!!!!!!!!!!!!!!!!!!!
select *
,前6个月销量=(
select sum(销量) from 表
where 产品类型=a.产品类型
and datediff(month,a.销售日期+'-1',销售日期+'-1') between 1 and 6) --这里a.在前
from 表 a
Sorry
,前6个月销量=(
select sum(销量) from 表
where 产品类型=a.产品类型
and datediff(month,销售日期+'-1',a.销售日期+'-1') between 1 and 6)
from 表 a
from t a
2楼的没有考虑楼主的日期是不完整的年月 --》格式“2002-1”这样不能直接进行日期运算的
3楼的统计会把前6个月和>销售日期的都统计到前6个月中 --》当日期是大于当前日期时,会是负数,负数自然<6了