日期:2014-05-18 浏览次数:20428 次
declare @a table(序号 CHAR(3),金额 INT ) insert @a select '003', 2000 insert @a select '043', 2100 insert @a select '030', 1300 insert @a select '047', 1000 insert @a select '065', 2500 insert @a select '072', 1000 insert @a select '034', 1400 insert @a select '100', 2340 insert @a select '013', 2500 insert @a select '024', 500 insert @a select '056', 1200 insert @a select '049', 1800 insert @a select '390', 1900 insert @a select '304', 2760 insert @a select '234', 7800 select * from @a a where (select sum(金额) from @a where 序号<a.序号) <10000 order by 序号 序号 金额 ---- ----------- 013 2500 024 500 030 1300 034 1400 043 2100 047 1000 (所影响的行数为 6 行)
------解决方案--------------------
declare @a table(序号 CHAR(3),金额 INT ) insert @a select '003', 2000 insert @a select '043', 2100 insert @a select '030', 1300 insert @a select '047', 1000 insert @a select '065', 2500 insert @a select '072', 1000 insert @a select '034', 1400 insert @a select '100', 2340 insert @a select '013', 2500 insert @a select '024', 500 insert @a select '056', 1200 insert @a select '049', 1800 insert @a select '390', 1900 insert @a select '304', 2760 insert @a select '234', 7800 select *from @a a where (select sum(金额) from @a where 序号<a.序号) <=10000 or 序号 =(select min(序号) from @a) order by 序号 序号 金额 ---- ----------- 003 2000 013 2500 024 500 030 1300 034 1400 043 2100 047 1000 (所影响的行数为 7 行)
------解决方案--------------------
--原始数据:@A declare @A table(序号 varchar(3),金额 int) insert @A select '003',2000 union all select '043',2100 union all select '030',1300 union all select '047',1000 union all select '065',2500 union all select '072',1000 union all select '034',1400 union all select '100',2340 union all select '013',2500 union all select '024',500 union all select '056',1200 union all select '049',1800 union all select '390',1900 union all select '304',2760 union all select '234',7800 /* 求:按照序号排序,输入金额之和恰好大于等于10000的记录。 意思是:输出的记录再加一条就太多了,少一条就不够10000。 */ select * from @A where 序号<=(select min(序号) from @A a where (select sum(金额) from @A where 序号<=a.序号)>=10000) /* 序号 金额 ---- ----------- 003 2000 043 2100 030 1300 047 1000 034 1400 013 2500 024 500 (所影响的行数为 7 行) */