获取行数限制值 sql php

Get count of rows limit value sql php

我有一笔 sql table 交易,数据如下

  id| value
   1| 0.1
   2| 0.5
   3| 0.9
   4| 0.3

如何进行 SQL 查询,以便在 php 中将条目数限制为总值 0.8(按 id 升序)。 例如:-

COUNT id FROM trade WHERE SUM(value) > 0.8 by id ASC

结果应该是

 3

在我看来你需要聚合函数和累计总和需要过滤你想要的结果

 set @csum := 0.0;
select count(id) from
(

select id,@csum := @csum + value as sum_val   from t 
 order by id
 ) t1
where  sum_val <1.3

http://sqlfiddle.com/#!9/abf460/2

count(id)
 3

你需要做累加判断,因为你的mysql版本不支持window函数所以解法会有点难读,因为你需要写子查询而不是window 函数。

通过Id列累加,然后在子查询中得到MIN(ID),当Id = 3值大于0.8.

最终得到小而等于的 Id MIN(ID) 你会得到你期望的结果。

CREATE TABLE trade(
   id  INT,
    value FLOAT
);

INSERT INTO trade VALUES(1,0.1);
INSERT INTO trade VALUES(2,0.5);
INSERT INTO trade VALUES(3,0.9);
INSERT INTO trade VALUES(4,0.3);

查询 1:

SELECT COUNT(*)
FROM trade t1
WHERE t1.id <= (
SELECT MIN(ID) FROM (
 SELECT ID,(
    SELECT SUM(tt.value) 
    FROM trade tt
    WHERE tt.id <= t1.id  
  ) total
  FROM trade t1
) t1
where total > 0.8
)

Results:

| COUNT(*) |
|----------|
|        3 |