一个查询:高手伸手啊!
表A:序号,金额
003 2000
043 2100
030 1300
047 1000
065 2500
072 1000
034 1400
100 2340
013 2500
024 500
056 1200
049 1800
390 1900
304 2760
234 7800
求:按照序号排序,输入金额之和恰好大于等于10000的记录。
意思是:输出的记录再加一条就太多了,少一条就不够10000。
[解决办法]
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', 7800select * from @a a where (select sum(金额) from @a where 序号<a.序号) <10000 order by 序号序号 金额 ---- ----------- 013 2500024 500030 1300034 1400043 2100047 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', 7800select *from @a a where (select sum(金额) from @a where 序号<a.序号) <=10000 or 序号 =(select min(序号) from @a)order by 序号序号 金额 ---- ----------- 003 2000013 2500024 500030 1300034 1400043 2100047 1000(所影响的行数为 7 行)
[解决办法]
--原始数据:@Adeclare @A table(序号 varchar(3),金额 int)insert @Aselect '003',2000 union allselect '043',2100 union allselect '030',1300 union allselect '047',1000 union allselect '065',2500 union allselect '072',1000 union allselect '034',1400 union allselect '100',2340 union allselect '013',2500 union allselect '024',500 union allselect '056',1200 union allselect '049',1800 union allselect '390',1900 union allselect '304',2760 union allselect '234',7800/*求:按照序号排序,输入金额之和恰好大于等于10000的记录。 意思是:输出的记录再加一条就太多了,少一条就不够10000。*/select * from @A where 序号<=(select min(序号) from @A a where (select sum(金额) from @A where 序号<=a.序号)>=10000)/*序号 金额 ---- ----------- 003 2000043 2100030 1300047 1000034 1400013 2500024 500(所影响的行数为 7 行)*/