12:38 2014/3/9 SQL Server技术交流(213291913)
有没有遇到这样的问题
表格2是结果,产品的汇总是类型不定的,有可能是'ABC','BC','D'多种可能都有,如何写SQL语句
我想到就是用游标,然后根据结果一条一条匹配。在表格1中增加一个汇总列,最后汇总成表2的样子。
有没有更好的方法呢?
下面是群友给出的答案
1 declare @temp table(产品 varchar(10),年 int,月 int,销量 int) 2 insert into @temp(产品,年,月,销量) 3 values('A',2013,1,23), 4 ('B',2013,1,1), 5 ('C',2013,1,23), 6 ('D',2013,1,3), 7 ('D',2013,2,8) 8 declare @temp1 table(产品 varchar(10),年 int,月 int,销量 int) 9 insert into @temp1(产品,年,月) 10 values('ABC',2013,1), 11 ('AB',2013,1), 12 ('ABD',2013,1), 13 ('BCD',2013,1), 14 ('CD',2013,2) 15 update @temp1 set 销量=( 16 select sum(销量) from @temp a 17 where charindex(a.产品,b.产品)>0 and a.年=b.年 and a.月=b.月) 18 from @temp1 b 19 select * from @temp 20 select * from @temp1