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
View Code

相关文章:

  • 2021-12-03
  • 2022-02-21
  • 2021-08-30
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-14
  • 2021-04-23
  • 2021-12-15
  • 2021-11-24
  • 2022-01-17
  • 2022-02-09
相关资源
相似解决方案