如何在最后一行进行修正的行之间平均分割数字。假设数字是100,并且有11行。我将不得不将修正添加到最后一行。 注意:只要一行包含更正
,就不必是最后一行 select cost/count from table
将修正添加到最后一行除外。
有什么建议吗?
答案 0 :(得分:2)
您可以使用简单的子查询执行此操作。例如
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
答案 1 :(得分:1)
一个数字(任何数字,只需在集合中替换它)
select 100 / cast((select count(*) from #split) as float) as number_between_row_count
更新: 纠正:
drop table #split
drop table #split2
create table #split (lineNumber float, valueTest float)
insert into #split values ('1','20'),('2','25'),('3','50'),
('4','22'),('5','100'),('6', '4'),('7','90'),('8','75'),('9','42'),('10','3'),('11','66')
update #split
set valueTest = 100
select *, cast(valueTest / cast(round ((select count(*) from #split),0)as int)as int)as div into #split2 from #split
update #split2
set div = (cast (div as int) +
(cast (valueTest as int) % cast(div as int)))
where lineNumber = (select top 1 lineNumber from #split2 order by lineNumber desc)
select * from #split2
给出:
LineNumber ValueTest div
1 100 9
2 100 9
3 100 9
4 100 9
5 100 9
6 100 9
7 100 9
8 100 9
9 100 9
10 100 9
11 100 10