表1
年度 编码 总数量
2001 0001
2001 0002
2001 0003
...
2005 0006表2
时间 编码 数量
2001-02-01 0001 22
2001-01-12 0002 56
2001-05-04 0001 32
2002-01-01 0003 65
...
2005-12-11 0001 11表1中 年度和编码 都为 字符型,总数量为 float
表2中 时间为 datetime, 编码为 字符型,数量为 float现在想这样
把表2 按年度 编码, 统计数量(sum),然后写入到表1中的总数量列,而且要求不能建临时表..
因为表1还有其他的统计字段,所以不能把表1删了重建新表.想一天了,还是不会,各位高手指教啊
年度 编码 总数量
2001 0001
2001 0002
2001 0003
...
2005 0006表2
时间 编码 数量
2001-02-01 0001 22
2001-01-12 0002 56
2001-05-04 0001 32
2002-01-01 0003 65
...
2005-12-11 0001 11表1中 年度和编码 都为 字符型,总数量为 float
表2中 时间为 datetime, 编码为 字符型,数量为 float现在想这样
把表2 按年度 编码, 统计数量(sum),然后写入到表1中的总数量列,而且要求不能建临时表..
因为表1还有其他的统计字段,所以不能把表1删了重建新表.想一天了,还是不会,各位高手指教啊
set
总数量=b.总数量
from
表1 a,
(select year(时间) as 年度,编号,sum(数量) as 总数量 from 表2 group by year(时间),编号) b
where
a.年度=b.年度 and a.编号=b.编号
from table1 a
left join
(select rtrim(year(时间)) as 年度,编码,sum(数量) as 数量
from table2 group by rtrim(year(年度)),编码) b
on a.年度 = b.年度 and a.编码 = b.编码
from 表1 a
join (
select convert(varchar(4),时间,120) as 年度 ,编码,sum(数量) 总数量
from 表2 group by convert(varchar(4),时间,120) ,编码
) b on a.年度=b.年度 and a.编码 =b.编码
group by rtrim(year(年度))
应为
group by rtrim(year(时间))
------------------------------------------------------------
update a set 总数量 = isnull(b.数量,0)
from table1 a
left join /*左联接*/
(select rtrim(year(时间)) as 年度,编码,sum(数量) as 数量
from table2 group by rtrim(year(时间)),编码) b
on a.年度 = b.年度 and a.编码 = b.编码