日期:2014-05-18  浏览次数:20465 次

sql,求和小于一定值的数据行
求SQL 写法:
表 t
 字段ID, 字段V
  0 3
  1 7
  2 4
  3 8
  4 10

求 V 累计到 20 的记录
效果如:
select * from t where sum(v) < 20 order by ID

不要用存储过程,如何构建SQL


------解决方案--------------------
SQL code
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 行受影响)
**/

------解决方案--------------------
SQL code

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