请帮助我。
以下是原始数据:
uid | id | value |
1 | a | 389 |
2 | b | 201 |
3 | c | 170 |
如果......当参考值为'200'
如何使它像这样出来?
mysql ..
no| uid | id | value | cut
1 | 1 | a | 200 | 200
2 | 1 | a | 189 | 200
3 | 2 | b | 200 | 200
4 | 2 | b | 1 | 200
5 | 3 | c | 170 | 200
救救我!!!!
答案 0 :(得分:2)
如果您使用的是MySQL 8或更高版本,则递归CTE可以提供帮助:
CREATE DATABASE test;
USE test;
CREATE TABLE TestData (uid INTEGER, id VARCHAR(8), value INTEGER);
INSERT INTO TestData VALUES (1, 'a', 389);
INSERT INTO TestData VALUES (2, 'b', 201);
INSERT INTO TestData VALUES (3, 'c', 170);
INSERT INTO TestData VALUES (4, 'd', 550);
-- Set up an auto-incrementing row number
SET @row_num = 0;
WITH RECURSIVE cte (uid, id, value, remainder) AS (
-- start with a copy of the table, but adding another column for the value that is at most 200
SELECT a.uid, a.id, LEAST(a.value, 200), a.value AS "remainder" FROM TestData a
UNION
-- repeatedly select from the previous result set, meanwhile decrementing the "remainder" column
SELECT uid, id, LEAST(remainder - 200, 200), remainder - 200 FROM cte WHERE remainder > 200
)
-- select the actual data that we care about
SELECT (@row_num := @row_num + 1) AS no, uid, id, value, 200 AS "cut" FROM cte ORDER BY id, value DESC;
这将产生下表:
no | uid | id | value | cut
1 | 1 | a | 200 | 200
2 | 1 | a | 189 | 200
3 | 2 | b | 200 | 200
4 | 2 | b | 1 | 200
5 | 3 | c | 170 | 200
6 | 4 | d | 200 | 200
7 | 4 | d | 200 | 200
8 | 4 | d | 150 | 200
答案 1 :(得分:1)
如何?
SET @row_num = 0;
SELECT (@row_num := @row_num + 1) AS "no",uid,id,valueA, "200" as cut FROM
(SELECT uid,id,IF(valueA/200 > 1,200,valueA) AS "valueA" FROM tableA UNION ALL
SELECT uid,id,IF(valueA/200 > 2,200,valueA-200) AS "valueA" FROM tableA UNION ALL
SELECT uid,id,IF(valueA/200 > 3,200,valueA-400) AS "valueA" FROM tableA) a
WHERE valueA > 0
ORDER BY uid,id,valueA DESC;
如果valueA除以200等于大于1,则将返回200,否则将仅返回valueA中的值。这是UNION ALL
查询中的第一个语法。
第二个条件是我添加了另一个条件,好像valueA除以200等于不等于2,它将返回valueA-200。您可以尝试执行UNION ALL
查询以查看结果。
这不是最好的方法,我敢肯定那里有更好的解决方案,但是我可以使用这种方法来工作。您可以将其用作临时解决方案,或者至少给您一些想法。
答案 2 :(得分:0)
考虑编写存储过程,而不是用纯SQL来完成所有操作,或者只是从表中选择行,然后在php中执行以下操作:
据我所知,您正在寻找这个:
no = 1
For each row in the result set
for i = 0 to int(value/cut)
output the row with value set to cut
no += 1
output the row with value set to mod(value, cut)
no += 1