mysql - 行之间的sql分割数

标签 mysql sql

<分区>

我应该如何在最后一行更正的行之间平均拆分数字。假设数字是 100,则有 11 行。我将不得不在最后一行添加更正。 注意:不一定是最后一行,只要一行包括更正即可

从表中选择成本/计数 除了将更正添加到最后一行之外,将起作用。

有什么建议吗?

最佳答案

您可以使用简单的子查询来完成此操作。例如

select floor(100 / (select count(*) from f)) as number_between_row_count;

然后您可以设置一个用户变量并更新最后一行,例如;

set @number_between_row_count = 0;
select @number_between_row_count:=floor(100 / (select count(*) from f));
update f set bar = @number_between_row_count+1 order by id desc limit 1;
update f set bar = @number_between_row_count where bar is null;

我们的用户变量将保存计算(即:(100/5) = 20),因此将写入 20。

http://dev.mysql.com/doc/refman/5.7/en/user-variables.html

编辑

例如,我们有下表;

CREATE TABLE `33566497` (
  `number` int(11) DEFAULT NULL,
  `t` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('1', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('2', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('3', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('4', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('5', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('6', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('7', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('8', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('9', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('10', NULL);
INSERT INTO `test`.`33566497` (`number`, `t`) VALUES ('11', NULL);

我们有 11 条记录。前 10 条记录需要 t = 9,最后一条记录需要 t = 10,然后我们运行;

set @number_between_row_count = 0;
select @number_between_row_count:=floor(100 / (select count(*) from `33566497`)); #calc the number (and round down so it's a whole number)
update `33566497` set t = @number_between_row_count+1 order by number desc limit 1; #update the last record to number + 1 because we need 10, not 9
update `33566497` set t = @number_between_row_count where t is null; #set the rest to 9

enter image description here

关于mysql - 行之间的sql分割数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33566497/

相关文章:

php - 具有角色、角色特定字段的 MySQL 用户?

MySQL 选择信息

php - 当我尝试 CakePHP 方式时,Cakephp 2.8.x 查询访问冲突。正常查询有效

mysql - 多类别数据库设计

mysql - 来自自连接表和另一个 MySQL 的结果集

mysql - 查询中的 SQL 语法错误

mysql - mysql子查询中的未知列

mysql - 如何查找其中包含某些行值的列/表

php - 从同一列中的多个mysql行中查找整数总和

sql - 如何在不使用 CASE WHEN 的情况下将 GROUP BY 作为参数?