日期:2014-05-18 浏览次数:20465 次
if object_id('[t]') is not null drop table [t] go create table [t]([ID] int,[V] int) insert [t] select 0,3 union all select 1,7 union all select 2,4 union all select 3,8 union all select 4,10 go select * from t a where (select sum(v) from t where t.id<=a.id)<20 order by id /** ID V ----------- ----------- 0 3 1 7 2 4 (3 行受影响) **/
------解决方案--------------------
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'tba') BEGIN DROP TABLE tba END GO CREATE TABLE tba ( ID INT, Value INT ) GO INSERT INTO tba SELECT 0, 3 UNION SELECT 1, 7 UNION SELECT 2, 4 UNION SELECT 3, 8 UNION SELECT 4, 10 SELECT ID,value FROM tba AS A WHERE (SELECT SUM(value) FROM tba WHERE ID <= A.ID) < 20 ID value 0 3 1 7 2 4 --如果要累计的效果 SELECT ID,value,(SELECT SUM(value) FROM tba WHERE ID <= A.ID) AS total FROM tba AS A ID value total 0 3 3 1 7 10 2 4 14 3 8 22 4 10 32