日期:2014-05-18 浏览次数:20549 次
--生成测试数据: declare @a table (a int ,flag varchar(20),n int) declare @b table (a int,flagmt varchar(20),m int) insert @a select 1,'lbl1',10 union all select 1,'lbl2',25 union all select 2,'lbl3',20 select * from @a a flag n ----------- -------------------- ----------- 1 lbl1 10 1 lbl2 25 2 lbl3 20 insert @b select 1,'seq1',10 union all select 1,'seq2',20 union all select 1,'seq3',30 union all select 2,'seq1',6 union all select 2,'seq2',10 select * from @b a flagmt m ----------- -------------------- ----------- 1 seq1 10 1 seq2 20 1 seq3 30 2 seq1 6 2 seq2 10 --我想得到的结果: ----------- ---- ---- ----------- 1 lbl1 seq1 10 1 lbl2 seq2 20 1 lbl2 seq3 5 2 lbl3 seq1 6 2 lbl3 seq2 14 简单分析下: 参照@a表的a列,a列相同的为一组 从上到下和@b表中去比较。第一条比完了,比较第二条,。。 注:如果@a表中按照a列分组的 n的和 比 @b中大的话,比较完后,把大的那一部分值加到@b表中,同一组的随便一列上就行
declare @a table (a int ,flag varchar(20),n int) declare @b table (a int,flagmt varchar(20),m int) insert @a select 1,'lbl1',10 union all select 1,'lbl2',25 union all select 2,'lbl3',20 insert @b select 1,'seq1',10 union all select 1,'seq2',20 union all select 1,'seq3',30 union all select 2,'seq1',6 union all select 2,'seq2',10 ;with t1 as ( select rn=row_number()over(partition by a order by flag),* from @a) ,t2 as (select rn=row_number()over(partition by a order by flagmt),* from @b) select t2.a,isnull(t1.flag,(select max(flag) from t1 t where t.a=t2.a)),t2.flagmt, (case when t1.a is null then (select sum(n) from t1 where a=t2.a)-(select sum(m) from t2 t where t.a=t2.a and t.rn in(select rn from t1 o where o.a=t.a)) else t2.m end ) from t1 right join t2 on t1.rn=t2.rn and t1.a=t2.a /* a flagmt ----------- -------------------- -------------------- ----------- 1 lbl1 seq1 10 1 lbl2 seq2 20 1 lbl2 seq3 5 2 lbl3 seq1 6 2 lbl3 seq2 14 (所影响的行数为 5 行)*/
------解决方案--------------------
看不懂~~~~
------解决方案--------------------
太强大了,,我也没看懂了。。。哎。。
------解决方案--------------------
还有一个疑问,如果@a中的第一条改为8,即不够对@b中的一行进行分配时,需要像这样拆开吗?
--- @a a flag n ----------- -------------------- ----------- 1 lbl1 8 -- 10 改为 8 1 lbl2 25 2 lbl3 20 --- @b a flagmt m ----------- -------------------- ----------- 1 seq1 10 1 seq2 20 1 seq3 30 2 seq1 6 2 seq2 10 -- 结果 ----------- ---- ---- ----------- 1 lbl1 seq1 8 1 lbl2 seq1 2 1 lbl2 seq2 20 1 lbl2 seq3 3 2 lbl3 seq1 6 2 lbl3 seq2 14